here is a code:
try {
FileOutputStream fout=new FileOutputStream("path");
javaClassFun(url,fout);
fout.close();
} catch (MalformedURLException ex) {
System.err.println("Invalid URL"+ex);
} catch (IOException e) {
System.err.println("Input/Output error"+e);
}
when i cut the last catch block and paste it after try block it gives unreachable catch block error.
I want to know what is the reason behind this.
The reason why is that MalformedURLException inherits from IOException.
try {
//call some methods that throw IOException's
} catch (IOException e) {
// This will catch MalformedURLException since it is an IOException
} catch (MalformedURLExceptionn ex) {
// Will now never be caught! Ah!
}
If you want to design catch blocks which properly handle an exception hierarchy, you need to put the super class last and the subclasses which you want to handle individually prior to it. See the example below for how to handle the IOException class hierarchy as it pertains to your code.
try {
//call some methods that throw IOException's
} catch (MalformedURLExceptionn ex) {
// This will catch MalformedURLException
} catch (IOException e) {
// This will catch IOException and all other subclasses besides MalformedURLException
}
Related
I am able to catch RuntimeException or subclass of it with below code:
try {
//code that throws subclass of RuntimeException
throw new ChildRuntimeException("try");
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
But I am getting error with below code and not able to catch RuntimeException in Exception catch block.
try {
// code that throws subclass of Exception
throw new ChildExceptionClass("try");
} catch (ChildExceptionClass ex) {
throw new RuntimeException(ex.getMessage());
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
I searched for the same type of questions but did not find a suitable answer. Can
anyone explain why the behaviour is different?
In the second example you are throwing a childRuntimeException, which is caught, but then a new runtimeException is thrown. This block has no "catch" clause, so the exception is thrown and not caught.
The second catch is relevant for the "try" block, not for the "catch" block.
What I guess you probably want to do is:
try { // code that throws subclass of Exception
throw new ChildExceptionClass("try");
} catch (ChildExceptionClass ex) {
try {
throw new RuntimeException(ex.getMessage());
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
Do you understand the difference?
I am facing problem while reading data from .xlsx file as the catch (InvalidFormatException e) return error for exception as "Unreachable catch block for InvalidFormatException. This exception is never thrown from the try statement body"
I have used openxml4j import which I think is necessary
public static Object[][] getTestData(String sheetname) {
FileInputStream file = null;
try {
file = new FileInputStream(TEST_DATA_SHEET_PATH);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
book = WorkbookFactory.create(file);
} catch (InvalidFormatException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
It is expected that there should not be error for the InvalidFormatException and data should be red from .xlsx file
try {
book = WorkbookFactory.create(file);
} catch (InvalidFormatException e) {
e.printStackTrace();
}
The code inside this try block, does not throw an InvalidFormatException. That is why you are getting the error message.
Perhaps your intention is using that catch block somewhere else.
From the documnetation:
https://poi.apache.org/apidocs/dev/org/apache/poi/ss/usermodel/WorkbookFactory.html#create-java.io.File-
This is the methods signiture:
public static Workbook create(java.io.File file)
throws java.io.IOException,
EncryptedDocumentException
As you can see above, no InvalidFormatExceptionis thrown from this method.
This happens if the IDE can't see or understand that a specific ( InvalidFormatException ) exception is thrown in a given code segment.
You can simply solve this problem by joining you try blocks:
try {
book = WorkbookFactory.create(file);
} catch (Exception e) {
e.printStackTrace();
}
with this approach you can also could clean up and join your code like this if your error handling allows it:
try {
file = new FileInputStream(TEST_DATA_SHEET_PATH);
book = WorkbookFactory.create(file);
} catch (Exception e) {
e.printStackTrace();
}
Assuming we are talking about all the exceptions that extends base Exception class,
is:
try {
some code;
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
catch (MyOwnException e)
{
e.printStackTrace();
}
same as:
try {
some code;
}
catch (Exception e) {
e.printStackTrace();
}
I am wondering in which case I MUST use the former one?
In the 2nd option Exception will catch all exception, not only those explicitly listed in the first option.
Use the 1st option if you want to catch only selected exceptions, and respond differently to each.
If you want to catch only selected exceptions, and have the same response to all of them, you could use:
catch (InterruptedException | ExecutionException | MyOwnException e)
{
e.printStackTrace();
}
It is good practice to use Exception sub classes rather than Exception class. If you use Exception then it would be difficult to debug.
Here is a link for reference
http://howtodoinjava.com/best-practices/java-exception-handling-best-practices/#3
If you have multiple exceptions which all are extending from...we'll say IndexOutOfBoundsException, then unless you specifically want to print a different message for StringIndexOutOfBoundsException or another sub-class you should catch an IndexOutOfBoundsException. On the other hand if you have multiple exceptions extending from the Exception class, it is proper format to create a multi-catch statement at least in JDK 1.8:
try {
// Stuff
}catch(InterruptedException | ClassNotFoundException | IOException ex) {
ex.printStackTrace();
}
The former one where you create multiple catch statements is if you were trying to do what I said before.
try {
// Stuff
}catch(StringIndexOutOfBoundsException se) {
System.err.println("String index out of bounds!");
}catch(ArrayIndexOutOfBoundsException ae) {
System.err.println("Array index out of bounds!");
}catch(IndexOutOfBoundsException e) {
System.err.println("Index out of bounds!");
}
I have the following:
public void method(){
try {
methodThrowingIllegalArgumentException();
return;
} catch (IllegalArgumentException e) {
anotherMethodThrowingIllegalArgumentException();
return;
} catch (IllegalArgumentException eee){ //1
//do some
return;
} catch (SomeAnotherException ee) {
return;
}
}
Java does not allow us to catch the exception twice, so we got compile-rime error at //1. But I need to do exactly what I try to do:
try the methodThrowingIllegalArgumentException() method first and if it fails with IAE, try anotherMethodThrowingIllegalArgumentException();, if it fails with IAE too, do some and return. If it fails with SomeAnotherException just return.
How can I do that?
If the anotherMethodThrowingIllegalArgumentException() call inside the catch block may throw an exception it should be caught there, not as part of the "top level" try statement:
public void method(){
try{
methodThrowingIllegalArgumentException();
return;
catch (IllegalArgumentException e) {
try {
anotherMethodThrowingIllegalArgumentException();
return;
} catch(IllegalArgumentException eee){
//do some
return;
}
} catch (SomeAnotherException ee){
return;
}
}
try {
throw new SomeException();
}
catch (SomeException e) {
System.out.println("reached once");
throw e;
}
catch (Exception e) {
System.out.println("reached twice");
}
This code only displays "reached once" even though the exception was thrown again inside the first catch clause. How can this be fixed in order that both catch clauses be executed?
PS: The above code was a general question I had, and I had to apply it to a much larger code with about 5 or 6 catch clauses that catch different exceptions, but in the end, at a certain point in a loop I need the exception to be thrown again.
Simply add another try catch in the catch.
try {
try {
throw new NullPointerException();
} catch (NullPointerException e) {
System.out.println("reached once");
throw e;
}
} catch (SomeOtherException ex) {}
You'll have to sorround all code that can throw an Exception with a try/catch block
try {
throw new NullPointerException();
}
catch (NullPointerException e) {
System.out.println("reached once");
try{
throw e;
}
catch (Exception ex) {
System.out.println("reached twice");
}
}