I'm building a custom exception which basically is thrown if an array doesn't contain 5 strings. This is what I have so far. The only exception that really matters is the custom one as I just have to show that that exception is thrown if the array doesn't contain the 5 strings after the input file was split. Any help would be appreciated. Thanks!
package exceptions;
import java.io.File;
import java.util.Scanner;
public class Exceptions {
public static void main(String[] args) {
String input, formattedInt, field[];
int recordNumber = 0;
int length;
Scanner inputFile;
try {
inputFile = new Scanner(new File("data.txt"));
while (inputFile.hasNextLine()) {
recordNumber++;
formattedInt = String.format("%2d", recordNumber);
input = inputFile.nextLine();
field = input.split(",");
length = field.length;
if (field.length != 5) throw new CustomException(field.length);
System.out.println("Record #" + formattedInt + ": " + input);
}
} catch (Exception e) {
System.out.println("Error! Problem opening file.\nError was: " + e);
} catch (CustomException ce) {
System.out.println(ce);
}
}
}
CustomException.java
package exceptions;
public class CustomException extends Exception {
private int fieldcount;
public CustomException(int fieldCount) {
super("Invalid Count: " + fieldCount);
}
public int getCount() {
return fieldcount;
}
}
CustomException extends Exception so any CustomException will be caught in the first catch block.
Rearrange your blocks so the catch(CustomException e) block comes before the catch(Exception e) block
Related
Instead of the try{}catch(Exception e){} method, is there a way to just state a custom message that replaces the exception message when exceptions like InputMismatchException, NoSuchElementException etc. occurs anywhere on the program?
EDIT: I want another method because if I use try{}catch(Exception e){} method than I will have to do it everywhere and the code also becomes longer.
For example:
public static String genderOutput()
{
try
{
System.out.print("\nMale - 1 \nFemale - 2 \n\nEnter either 1 or 2: ");
int genderInput = userInput.nextInt();
if(genderInput == 1)
{
String userGender = "Mr.";
return userGender;
}
else if(genderInput == 2)
{
String userGender = "Mrs.";
return userGender;
}
else
{
String userGender = " ";
return userGender;
}
}
catch (Exception e)
{
return null;
}
}
I have this function, now if there were multiple functions in a class like this then I would have to have the try{}catch(Exception e){} method everywhere. Wouldn't it be more efficient if you can just replace the exception message with your own and when such exception occurs which has a custom message stated to them then it would just throw out the custom message instead. This way, the code will be shorter as well.
SOLUTION TO MY PROBLEM:
public class Test
{
public static Scanner userInput = new Scanner(System.in);
public static String titleName = "TheRivalsRage";
public static String exitLevelMessage = "Program exited!";
public static String errorMessageTitle = "\n[Error] ";
public static String intInputMismatchException = "Please enter an Integer Value!";
public static String intNoSuchElementException = "Please enter either '1' or '2' without the quotes!";
public static String lineNoSuchElementException = "Please enter something!";
public static String bothIllegalStateException = "Scanner closed unexpectedly!";
public static void main(String[] args)
throws Exception
{
String usernameOutput;
String userGender;
try
{
System.out.print("Enter your username: ");
usernameOutput = userInput.nextLine();
userGender = genderOutput();
userInput.close();
}
catch(IllegalStateException e)
{
throw new IllegalStateException(errorMessageTitle + bothIllegalStateException);
}
if(userGender == null)
{
noSuchElementException();
}
else
{
System.out.println("\nWelcome " + userGender + " " + usernameOutput + " to " + titleName);
}
}
public static String genderOutput()
{
String userGender;
int genderInput;
System.out.print("\nMale - 1 \nFemale - 2 \n\nEnter either 1 or 2: ");
try
{
genderInput = userInput.nextInt();
}
catch(InputMismatchException e)
{
genderInput = 0;
inputMismatchException();
}
if(genderInput == 1)
{
userGender = "Mr.";
}
else if(genderInput == 2)
{
userGender = "Mrs.";
}
else
{
userGender = null;
}
return userGender;
}
public static void inputMismatchException()
throws InputMismatchException
{
throw new InputMismatchException(errorMessageTitle + intInputMismatchException);
}
public static void noSuchElementException()
throws NoSuchElementException
{
throw new NoSuchElementException(errorMessageTitle + intNoSuchElementException);
}
}
don't handle exception in each and every method just use throws Exception after method signature and handle it at end where the methods are being called.
and there in catch block you can throw your custom exception.
void method1() throws Exception{
//
}
void method2() throws Exception{
//
}
void finalmethod(){
try{
method1();
method2();
}catch(InputMismatchException e){
throw customExcpetion("custommessage1");
}catch(Exception e){
throw customExcpetion("custommessage2");
}
}
You need a try/catch.
However, you do not need to catch all exceptions separately, because the exceptions that you mention are all subclasses of RuntimeException. Hence, it is sufficient to make a single try/catch in your main to intercept RuntimeException, and print the replacement message:
public static void main(String[] args) {
try {
... // Actual code
} catch (RuntimeException ex) {
System.err.println("A runtime error has occurred.");
}
}
You can try Aspectj or Spring aop by creating around advice. You can replace message by catching exception inside advice and rethrow.
Check http://howtodoinjava.com/spring/spring-aop/aspectj-around-advice-example/
To know about how to use spring aop for anound advice
Java doesn't provide this feature out of the box but nobody prevents you to create a class that composes a Scanner object and that decorates methods that you are using as nextInt().
Inside the decorated method, invoke nextInt(), catch the exception that it may throw and handle it by returning null as in your question.
If it makes sense, you could even provide a nextInt() method with a default value as parameter if the input fails.
public class MyCustomScanner{
private Scanner scanner;
...
public Integer nextInt(){
try{
return scanner.nextInt()
}
catch(InputMismatchException e){
myStateObj.setErrorMessage("....");
return null;
}
}
public Integer nextInt(Integer defaultValue){
try{
return scanner.nextInt()
}
catch(InputMismatchException e){
myStateObj.setErrorMessage("....");
return defaultValue;
}
}
}
Now you can use the class in this way :
MyCustomScanner scanner = new MyCustomScanner();
Integer intValue = scanner.nextInt();
Integer otherIntValue = scanner.nextInt(Integer.valueOf(4));
I initially started programming in college and learnt vb.net. Now I have decided to make the move to Java and have some queries. In vb, the try catch statement is laid out as follows
try
Catch ex as exception
finally
End catch
but from the java website (https://docs.oracle.com/javase/tutorial/essential/exceptions/putItTogether.html)
i found that in java you use two catches like so:
try {
} catch (ExceptionType name) {
} catch (ExceptionType name) {
}
i was hoping someone could explain why you need two catches in java and what do the respective catches do/catch.
Thanks.
In Java, you can use multiple catch blocks.
It doesn't necessarily means you have to.
It depends on the code your have in the try block, and how many checked Exceptions it may potentially throw (or even unchecked Exceptions if you really want to catch that, typically you don't and you don't have to).
One bad practice is to use a single handler for general Exception (or worse, Throwable, which would also catch RuntimeExceptions and Errors):
try {
// stuff that throws multiple exceptions
}
// bad
catch (Exception e) {
// TODO
}
The good practice is to catch all potentially thrown checked Exceptions.
If some of them are related in terms of inheritance, always catch the child classes first (i.e. the more specific Exceptions), lest your code won't compile:
try {
// stuff that throws FileNotFoundException AND IOException
}
// good: FileNotFoundException is a child class of IOException - both checked
catch (FileNotFoundException fnfe) {
// TODO
}
catch (IOException ioe) {
// TODO
}
Also take a look at Java 7's multi-catch blocks, where unrelated Exceptions can be caught all at once with a | separator between each Exception type:
try (optionally with resources) {
// stuff that throws FileNotFoundException and MyOwnCheckedException
}
// below exceptions are unrelated
catch (FileNotFoundException | MyOwnCheckedException e) {
// TODO
}
Note
In this example you linked to, the first code snippet below Putting it all together may arguably be considered as sub-optimal: it does catch the potentially thrown Exceptions, but one of them is an IndexOutOfBoundsException, which is a RuntimeException (unchecked) and should not be handled in theory.
Instead, the SIZE variable (or likely constant) should be replaced by a reference to the size of the List being iterated, i.e. list.size(), in order to prevent IndexOutOfBoundsException from being thrown.
I guess in this case it's just to provide an example though.
The code that is on the page that is in link i have modified it with single exception. Problem here is that in this case you will not able to know that exception is where whether due to
IndexOutOfBoundsException or IOException
just you know that a exception occurs
import java.io.*;
import java.util.List;
import java.util.ArrayList;
public class ListOfNumbers {
public static void main(String... s) {
ListOfNumbers lon = new ListOfNumbers();
lon.writeList();
}
private List<Integer> list;
private static final int SIZE = 10;
public ListOfNumbers() {
list = new ArrayList<Integer>(SIZE);
for (int i = 0; i < SIZE; i++) {
list.add(new Integer(i));
}
}
public void writeList() {
PrintWriter out = null;
try {
System.out.println("Entering" + " try statement");
out = new PrintWriter(new FileWriter("e://OutFile.txt"));
for (int i = 0; i < SIZE; i++) {
out.println("Value at: " + i + " = " + list.get(i));
}
} catch (Exception e) {
System.err.println("Caught Exception: " + e.getMessage());
} finally {
if (out != null) {
System.out.println("Closing PrintWriter");
out.close();
} else {
System.out.println("PrintWriter not open");
}
}
}
}
Let us understand the concept it is better to know why the code fails due to which particular type of exception whether
IndexOutOfBoundsException or IOException
Now The Code with handling of different Exception
import java.io.*;
import java.util.List;
import java.util.ArrayList;
public class ListOfNumbers {
public static void main(String... s) {
ListOfNumbers lon = new ListOfNumbers();
lon.writeList();
}
private List<Integer> list;
private static final int SIZE = 10;
public ListOfNumbers() {
list = new ArrayList<Integer>(SIZE);
for (int i = 0; i < SIZE; i++) {
list.add(new Integer(i));
}
}
public void writeList() {
PrintWriter out = null;
try {
System.out.println("Entering" + " try statement");
out = new PrintWriter(new FileWriter("e://OutFile.txt"));
for (int i = 0; i < SIZE; i++) {
out.println("Value at: " + i + " = " + list.get(i));
}
} catch (IndexOutOfBoundsException e) {
System.err.println("Caught IndexOutOfBoundsException: " +
e.getMessage());
} catch (IOException e) {
System.err.println("Caught IOException: " + e.getMessage());
} finally {
if (out != null) {
System.out.println("Closing PrintWriter");
out.close();
} else {
System.out.println("PrintWriter not open");
}
}
}
}
Here we could come to know that whether it fails due to creation of file at location
e://OutFile.txt
drive Not on my system
error printed as
Caught Exception: e:\OutFile.txt (The system cannot find the path
specified) Entering try statement PrintWriter not open
Next Case
Now when i comment the line
list.add(new Integer(i));
import java.io.*;
import java.util.List;
import java.util.ArrayList;
public class ListOfNumbers {
public static void main(String... s) {
ListOfNumbers lon = new ListOfNumbers();
lon.writeList();
}
private List<Integer> list;
private static final int SIZE = 10;
public ListOfNumbers() {
list = new ArrayList<Integer>(SIZE);
for (int i = 0; i < SIZE; i++) {
// list.add(new Integer(i));
}
}
public void writeList() {
PrintWriter out = null;
try {
System.out.println("Entering" + " try statement");
out = new PrintWriter(new FileWriter("OutFile.txt"));
for (int i = 0; i < SIZE; i++) {
out.println("Value at: " + i + " = " + list.get(i));
}
} catch (IndexOutOfBoundsException e) {
System.err.println("Caught IndexOutOfBoundsException: " +
e.getMessage());
} catch (IOException e) {
System.err.println("Caught IOException: " + e.getMessage());
} finally {
if (out != null) {
System.out.println("Closing PrintWriter");
out.close();
} else {
System.out.println("PrintWriter not open");
}
}
}
}
then it clearly says that it fails for index out of bound exception
Entering try statement Caught IndexOutOfBoundsException: Index: 0,
Size: 0 Closing PrintWriter
So for the purpose of debugging the application properly and efficiently it is good.
I have created condition for the other type of exception
NoClassDefFoundError
java.lang.NoClassDefFoundError: ListOfNumbers
Caused by: java.lang.ClassNotFoundException: stackprac.ListOfNumbers
at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
Exception in thread "main" Process exited with exit code 1.
I have this code that have some methods for creating a file, adding data to the file and then read the file with scanner.
My problem is that I want it to run my three methods at once but it stops
at the method number two and does not read the file with readFile() method
createFile();
addResponses(file);
readFile(file);
I can not run these three together. It does not read the file. But if I take
the other methods away like this
//createFile();
//addResponses(file);
readFile(file);
Then the read file method works.
I hope you did understand my problem. Is there something wrong with my code?
import java.io.*;
import java.util.Formatter;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class Main {
static Formatter f;
static String sträng = " ";
static BufferedWriter output;
static File file;
static int nummer = 1;
static int counter = 0;
static private StringBuffer strBuff;
static InputStream is;
static FileWriter fw;
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws Exception {
createFile();
addResponses(file);
readFile(file);
}
public static int addResponse() {
if (nummer == 6) {
try {
output.close();
} catch (IOException ex) {
JOptionPane.showMessageDialog(null, ex.getMessage());
}
System.exit(0);
}
sträng = JOptionPane.showInputDialog("Numbers 1-5 to number " + nummer");
try {
return Integer.parseInt(sträng);
} catch (NumberFormatException f) {
return 6;
}
}
public static File createFile() {
try {
file = new File("numbers.txt");
f = new Formatter(file);
f.close();
} catch (SecurityException se) {
System.err.println("You dont have write access to this file");
System.exit(1);
} catch (Exception ex) {
System.err.println("Error opening or creating file");
System.exit(1);
}
return file;
}
public static void readFile(File x) {
try {
x = new File("numbers.txt");
Scanner in = new Scanner(x);
while (in.hasNextLine()) {
System.out.println(in.nextLine());
}
in.close();
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
public static void addResponses(File f) throws IOException {
try {
fw = new FileWriter(f, true);
output = new BufferedWriter(fw);
int x = addResponse();
if (nummer == 1) {
output.write(String.format("%s%10s\n", "Rating", " Frequency"));
}
while (x != -1) {
if (x > 0 && x < 6) {
output.write(String.format("%s%10s\n", nummer, sträng));
nummer++;
} else {
JOptionPane.showMessageDialog(null, "Input only numbers between 1-5");
}
x = addResponse();
}
output.close();
} catch (IOException io) {
JOptionPane.showMessageDialog(null, "Wrong");
}
}
}
after playing around with the code, I found out that in your addResponse() method , you have added System.exit(0); so baiscally program was terminating. I've change it to return -1 and it seems to be working.
by the way, this is a very bad coding practice, each method should do stuff seperately regarless of other method. in your case everything is so integerated that is very hard to root the problem. I recommend you looking at some coding convention.
this is how addResponse() method should be working:
public static File createFile() {
try {
file = new File("numbers.txt");
f = new Formatter(file);
f.close();
} catch (SecurityException se) {
System.err.println("You dont have write access to this file");
System.exit(1);
} catch (Exception ex) {
System.err.println("Error opening or creating file");
System.exit(1);
}
return file;
}
I use eclipse to help me code & I have been having issues with the error message "Syntax error on token(s), misplaced construct(s)" coming up, I'm not entirely sure what is wrong with my code.
The goal of this code is to write a program where a user enters their name and age and the program checks to see the age is between 0 and 125. If not, the program shows an error code (use Exception Class)
Here is my current code: Errors are showing up in lines 1 and 4
public class ThreadsUnitProject1 {
import java.lang.String;
import java.io.*;
public static void main(String args[]);
class InvalidAgeException extends Exception {
private static final long serialVersionUID = 1L;
public InvalidAgeException() {
super("The age you entered is not between 0 and 125");
}
}
class QuestionOne extends Thread {
public void main(String args[]) {
System.out.println("What is your name?");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String name;
try {
name = br.readLine();
}
catch(IOException e) {
System.out.println("Error: " + e);
System.exit(1);
}
System.out.println("Hello " + name + ", how old are you?");
String i;
int age;
try {
i = br.readLine();
age = Integer.valueOf(i);
}
catch(IOException e) {
System.out.println("Error: " + e);
System.exit(1);
}
catch(InvalidAgeException e) {
System.out.println("Error: " + e);
System.exit(1);
}
finally {
System.out.println("No errors found.");
}
}
}
}
Thank you thank you thank you for all of your help, I have been coding for awhile, but I'm new to Java.
Thanks again!
-Kristen
public static void main(String args[]) is a method it needs to create a block with curly braces. It doesn't contain the block in the ThreadsUnitProject1 class.
public static void main(String args[]){}
Also the import statements should be outside the class declaration.
Full Example
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class ThreadsUnitProject1 {
public static void main(String args[]) {
}
class InvalidAgeException extends Exception {
private static final long serialVersionUID = 1L;
public InvalidAgeException() {
super("The age you entered is not between 0 and 125");
}
}
class QuestionOne extends Thread {
public void main(String args[]) {
System.out.println("What is your name?");
BufferedReader br = new BufferedReader(new InputStreamReader(
System.in));
String name = "";
try {
name = br.readLine();
} catch (IOException e) {
System.out.println("Error: " + e);
System.exit(1);
}
System.out.println("Hello " + name + ", how old are you?");
String i;
int age;
try {
i = br.readLine();
age = Integer.valueOf(i);
} catch (IOException e) {
System.out.println("Error: " + e);
System.exit(1);
} finally {
System.out.println("No errors found.");
}
}
}
}
Use {} after public static void main(String args[]), not ;.
I am trying to use a bit of code I found at the bottom of this page. Here is the code in a class that I created for it:
import java.io.LineNumberReader;
import java.io.FileReader;
import java.io.IOException;
public class LineCounter {
public static int countLines(String filename) throws IOException {
LineNumberReader reader = new LineNumberReader(new FileReader(filename));
int cnt = 0;
String lineRead = "";
while ((lineRead = reader.readLine()) != null) {}
cnt = reader.getLineNumber();
reader.close();
return cnt;
}
}
My objective is to count the lines of a text file, store that number as an integer, then use that integer in my main class. In my main class I tried a few different ways of making this happen, but (being a new programmer) I am missing something. Here is the first thing I tried:
String sFileName = "MyTextFile.txt";
private int lineCount = LineCounter.countLines(sFileName);
With this attempt I get the error "unreported exception java.io.IOException; must be caught or declared to be thrown." I don't understand why I am getting this because as I can see the exception is declared in my "countLines" method. I tried to use a try catch block right under that last bit of code I posted, but that didn't work either (I don't think I did it right though). Here is my try catch attempt:
String sFileName = "MyTextFile.txt";
private int lineCount;{
try{
LineCounter.countLines(sFileName);
}
catch(IOException ex){
System.out.println (ex.toString());
System.out.println("Could not find file " + sFileName);
}
}
Please show me the way!
Initializer block is just like any bits of code; it's not "attached" to any field/method preceding it. To assign values to fields, you have to explicitly use the field as the lhs of an assignment statement.
private int lineCount; {
try{
lineCount = LineCounter.countLines(sFileName);
/*^^^^^^^*/
}
catch(IOException ex){
System.out.println (ex.toString());
System.out.println("Could not find file " + sFileName);
}
}
Also, your countLines can be made simpler:
public static int countLines(String filename) throws IOException {
LineNumberReader reader = new LineNumberReader(new FileReader(filename));
while (reader.readLine() != null) {}
reader.close();
return reader.getLineNumber();
}
Based on my test, it looks like you can getLineNumber() after close().
The reason you are getting the the IOException is because you are not catching the IOException of your countLines method. You'll want to do something like this:
public static void main(String[] args) {
int lines = 0;
// TODO - Need to get the filename to populate sFileName. Could
// come from the command line arguments.
try {
lines = LineCounter.countLines(sFileName);
}
catch(IOException ex){
System.out.println (ex.toString());
System.out.println("Could not find file " + sFileName);
}
if(lines > 0) {
// Do rest of program.
}
}
Your countLines(String filename) method throws IOException.
You can't use it in a member declaration. You'll need to perform the operation in a main(String[] args) method.
Your main(String[] args) method will get the IOException thrown to it by countLines and it will need to handle or declare it.
Try this to just throw the IOException from main
public class MyClass {
private int lineCount;
public static void main(String[] args) throws IOException {
lineCount = LineCounter.countLines(sFileName);
}
}
or this to handle it and wrap it in an unchecked IllegalArgumentException:
public class MyClass {
private int lineCount;
private String sFileName = "myfile";
public static void main(String[] args) throws IOException {
try {
lineCount = LineCounter.countLines(sFileName);
} catch (IOException e) {
throw new IllegalArgumentException("Unable to load " + sFileName, e);
}
}
}