Exception hierarchy/try-multi-catch - java

try {
throw new FileNotFoundException();
} catch (IOException e) {
e.printStackTrace();
}
catch (Exception e) {
e.printStackTrace();
}
Can someone tell me why the second catch block is not considered as unreachable code by the compiler? But in the following case:
try {
throw new FileNotFoundException();
} catch (Exception e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
The second catch block is considered unreachable?
After all, FileNotFoundException comes under IOException, just as it comes under Exception.
Edit Please clarify:
The compiler will know an exception is thrown by a method based on the method's throws clause. But it may not necessarily know the specific type of exception (under that class of exception). So if a method throws exception 'A', compiler won't know if the actual exception is 'A' or a subtype of 'A' because this is only determined at runtime. The compiler however will know that an exception of type 'X' is never thrown, so giving a catch block for X is erroneous. Is this right?

The compiler cannot assume that the only possible exception thrown from your try block will be a FileNotFoundException. That's why it doesn't consider the 2nd catch block to be unreachable in your first code sample.
What if, for some unknown reason, a RuntimeException gets thrown while creating the FileNotFoundException instance (entirely possible)? What then?
In your first code sample, that unexpected runtime exception would get caught by the 2nd catch block, while the 1st block would take care of the FileNotFoundException if it gets thrown.
However, in your 2nd code sample, any and all exceptions would get caught by the 1st catch block, making the 2nd block unreachable.
EDIT:
To better understand why the catch(Exception e) block in your first code is not considered unreachable by the compiler, try the following code, and notice how the the 2nd catch is definitely reachable:
public class CustomIOException extends IOException {
public CustomIOException(boolean fail) {
if (fail) {
throw new RuntimeException("the compiler will never know about me");
}
}
}
public static void main(String[] args) {
try {
throw new CustomIOException(true);
} catch(IOException e) {
System.out.println("Caught some IO exception: " + e.getMessage());
} catch(Exception e) {
System.out.println("Caught other exception: " + e.getMessage());
}
}
Output:
Caught other exception: the compiler will never know about me

TL;DR
The compiler considers that FileNotFoundException() may not be the only Exception thrown.
Explaination
JLS§11.2.3 Exception Checking
A Java compiler is encouraged to issue a warning if a catch clause can
catch (§11.2) checked exception class E1 and the try block
corresponding to the catch clause can throw checked exception class
E2, a subclass of E1, and a preceding catch clause of the immediately
enclosing try statement can catch checked exception class E3 where E2
<: E3 <: E1.
That means that if the compiler considers that the only exception possibly thrown by your catch block is a FileNotFoundException(), it will warn you about your second catch block. Which is not the case here.
However, the following code
try{
throw new FileNotFoundException();
} catch (FileNotFoundException e){
e.printStackTrace();
} catch (IOException e){ // The compiler warns that all the Exceptions possibly
// catched by IOException are already catched even though
// an IOException is not necessarily a FNFException
e.printStackTrace();
} catch (Exception e){
e.printStackTrace();
}
This happens because the compiler evaluates the try block to determine which exceptions has the possibility to be thrown.
As the compiler does not warn us on Èxception e, it considers that other exceptions may be thrown (e.g RunTimeException). Since it is not the compiler's work to handle those RunTimeExceptions, it lets it slip.
Rest of the answer is intersting to read to understand the mechanism behind exception-catching.
Schema
As you may see, Exception is high in the hierarchy so it has to be declared last after IOException that is lower in the hierarchy.
Example
Imagine having an IOException thrown. As it is inherited from Exception, we can say IOException IS-A Exception and so, it will always be catched within the Exception block and the IOException block will be unreachable.
Real Life Example
Let's say, you're at a store and have to choose pants. The seller tells you that you have to try the pants from the largest ones to the smallest ones and if you find one that you can wear (even if it is not your size) you must take it.
You'll find yourself buying pants too large for your size and you'll not have the chance to find the pants that fits you.
You go to another store : there, you have the exact opposite happening. You can choose your pants from smallest to largest and if you find one you can wear, you must take it.
You'll find yourself buying pants at your exact size.
That's a little analogy, a bit odd but it speaks for itself.
Since Java 7 : multi-catch
Since Java 7, you have the option to include all the types of Exceptions possibly thrown by your try block inside one and only catch block.
WARNING : You also have to respect the hierarchy, but this time, from left to right.
In your case, it would be
try{
//doStuff
}catch(IOException | Exception e){
e.printStackTrace();
}
The following example, which is valid in Java SE 7 and later,
eliminates the duplicated code:
catch (IOException|SQLException ex) {
logger.log(ex);
throw ex;
}
The catch clause specifies the types of exceptions that the block can
handle, and each exception type is separated with a vertical bar (|).

First case:
catch (IOException e) { // A specific Exception
e.printStackTrace();
}
catch (Exception e) { // If there's any other exception, move here
e.printStackTrace();
}
As you can see, first IOException is catched. This means we are aiming at just one specific exception. Then in second catch, we aim for any other Exceptions other than IOException. Hence its logical.
In second:
catch (Exception e) { // Move here no matter whatever exception
e.printStackTrace();
}
catch (IOException e) { // The block above already handles *Every exception, hence this won't be reached.
e.printStackTrace();
}
We catched any exception (whether its IOException or some other Exception), right in the first block. Hence second block will not be reached because everything is already included in first block.
In other words, in first case, we aim at some specific exception, than at any other exceptions. While in second case, we first aim at all/any Exception, than at a specific exception. And since we already dealt will all exceptions, having a specific exception later won't make any logical sense.

Related

why is the Catch exception e printing instead of doing what is in Try

I am confused why it is going to catch and print the error occurred message when I run my code since it runs and just prints the message I can't tell what the error could be
Note: this is my very first time using try and catch my professor told us to use it but haven't really learned how it works fully yet so I'm not sure if the problem is with that or if it's just with my code
public static void main (String [] args) {
try {
File file = new File("in.txt");
Scanner scanFile = new Scanner(file);
...
} catch(Exception e) {
System.out.println("Error");
}
}
Do not catch an exception unless you know what to do. It is common that you don't - most exceptions aren't 'recoverable'.
So, what do you do instead?
Simplest plan: Just tack throws Exception on your main method. public static void main(String[] args) methods should by default be declared to throws Exception, you need a pretty good reason if you want to deviate from this.
Outside of the main method, think about your method. Is the fact that it throws an exception an implementation detail (a detail that someone just reading about what the method is for would be a bit surprised by, or which could change tomorrow if you decide to rewrite the code to do the same thing but in a different way)? In that case, do not add that exception to the throws clause of your method. But if it is, just add it. Example: Any method whose very name suggests that file I/O is involved (e.g. a method called readFile), should definitely be declared to throws IOException. It'd be weird for that method not to throws that.
Occasionally you can't do that, for example because you're overriding or implementing a method from an interface or superclass that doesn't let you do this. Or, it's an implementation detail (as per 2). The usual solution then is to just catch it and rethrow it, wrapped into something else. Simplest:
} catch (IOException e) {
throw new RuntimeException("uncaught", e);
}
Note that the above is just the best default, but it's still pretty ugly. RuntimeException says very little and is not really catchable (it's too broad), but if you don't really understand what the exception means and don't want to worry about it, the above is the correct fire-and-forget. If you're using an IDE, it probably defaults to e.printStackTrace() which is really bad, fix that template immediately (print half the details, toss the rest in the garbage, then just keep on going? That's.. nuts).
Of course, if you know exactly why that exception is thrown and you know what to do about it, then.. just do that. Example of this last thing:
public int askForInt(String prompt) {
while (true) {
System.out.println(prompt + ": ");
try {
return scanner.nextInt();
} catch (InputMismatchException e) {
System.out.println("-- Please enter an integral number");
}
}
}
The above code will catch the problem of the user not entering an integer and knows what to do: Re-start the loop and ask them again, until they do it right.
Just add throws Exception to your main method declaration, and toss the try/catch stuff out.
There are a couple of problems with your current code:
catch (Exception e) {
System.out.println("Error occured...");
}
Firstly, you are not printing any information about the exception that you caught. The following would be better:
catch (Exception e) {
System.out.println(e.getMessage()); // prints just the message
}
catch (Exception e) {
System.out.println(e); // prints the exception class and message
}
catch (Exception e) {
e.getStackTrace(System.out); // prints the exception stacktrace
}
Secondly, for a production quality you probably should be logging the exceptions rather than just writing diagnostics to standard output.
Finally, it is usually a bad idea to catch Exception. It is usually better to catch the exceptions that you are expecting, and allow all others to propagate.
You could also declare the main method as throws Exception and don't bother to catch it. By default, JVM will automatically produce a stacktrace for any uncaught exceptions in main. However, that is a lazy solution. And it has the disadvantage that the compiler won't tell you about checked exceptions that you haven't handled. (That is a bad thing, depending on your POV.)
now null printed out.
This is why the 2nd and 3rd alternatives are better. There are some exceptions that are created with null messages. (My guess is that it is a NullPointerException. You will need a stacktrace to work out what caused that.)
Catching Exception e is often overly broad. Java has many built-in exceptions, and a generic Exception will catch all of them. Alternatively, consider using multiple catch blocks to dictate how your program should handle the individual exceptions you expect to encounter.
catch (ArithmeticException e) {
// How your program should handle an ArithmeticException
} catch (NullPointerException e) {
// How your program should handle a NullPointerException
}

Can a checked exception be used to throw an unchecked exception?

I am running the following code:
import java.io.FileNotFoundException;
import java.io.IOException;
class Basic1 {
int c;
void calculation(int a, int b) throws Exception {
c = a / b;
}
}
class Basic extends Basic1 {
void calculation(int a, int b) throws IOException {
c = a / b;
RuntimeException ae = new ArithmeticException();
throw ae;
}
public static void main(String[] args) {
int a = 10;
int b = 0;
int c;
Basic ba = new Basic();
try {
ba.calculation(a, b);
} catch (IOException e) {
System.out.println("Zero can't be there in the denominator. : IoException");
} catch (ArithmeticException e) {
System.out.println("Zero can't be there in the denominator. : Arthimetic Exception");
} catch (Exception e) {
System.out.println("Zero can't be there in the denominator. : Exception");
}
}
}
The program is compiling successfully and outputting "Zero can't be there in the denominator. : Arthimetic Exception" (output is as expected).
My question is how is the program able to compile successfully? Why am I not getting an error when I throw an IOException while inside calculation() I am creating a RuntimeException object?
My second question is given that the program enters the catch (ArithmeticException e) clause, is the compiler deciding at run time which catch will execute? Do I understand correctly?
For your first question, methods using the throws E (where E is some arbitrary checked exception) construct don't have to throw anything. All it means is that anyone calling your method has to be able to handle E, which allows your method to throw E without handling it. This would otherwise be a compilation error. Usually, the documentation of your method specifies when E is thrown. In the words of the JLS:
Essentially, for each checked exception that can result from execution of the body of a method or constructor, a compile-time error occurs unless its exception type or a supertype of its exception type is mentioned in a throws clause in the declaration of the method or constructor.
This doesn't say you must throw the given checked exception within the method body. Note that you can use throws with unchecked exceptions, but this has no effect on the program, as unchecked exceptions may be thrown anywhere without being handled. That's the point of them.
In your code, you throw a RuntimeException. Any class extending RuntimeException (including itself) is unchecked by definition. ArithmeticException is one of these, so you may assign it to a variable of type RuntimeException and then throw it without specifying it in the throws clause.
For your second question, I'll assume that the compiler doesn't optimise away the various catch clauses. In that case, no, the catch which is executed is not determined at compile time. When any exception is thrown in your program, it propagates up the stack until it is caught. If it isn't, it halts execution and the stack trace is printed to System.err. Since an ArithmeticException is thrown, the first catch clause does not match but the second one does, so is executed. The third one (catch (Exception e)) would match, but order matters with catch clauses and only one is executed, so that clause is not executed here.
However, in this case, it is not inconceivable that the compiler optimises away your catch clauses and directs the program straight to the code in the catch (ArithmeticException e) clause, as your method will always throw ArithmeticException. It must be considered, however, that any line of code may throw some obscure error like OutOfMemoryError; the compiler must allow for such edge cases when optimising.

What are the restriction for code inside catch block

So are there any specific restrictions for writting code inside catch block?
PS. This question was asked by my friend's java programming teacher on the exam.
In this feature, now you can catch multiple exceptions in single catch block. Before java 7, you was restricted to catch only one. To specify the list of expected exceptions a pipe (‘|’) character is used.
Lets understand using an example.
try
{
//Do some processing which throws NullPointerException; I am sending directly
throw new NullPointerException();
}
//You can catch multiple exception added after 'pipe' character
catch(NullPointerException | IndexOutOfBoundsException ex)
{
throw ex;
}
Remember: If a catch block handles more than one exception type, then the catch parameter is implicitly final. In this example, the catch parameter ex is final and therefore you cannot assign any values to it within the catch block.
According to JLS:
CatchClause:
catch ( {VariableModifier} CatchType Identifier ) Block
So, you can write anything you can write in any other block.

Java: catching specific Exceptions

say I have the following
try{
//something
}catch(Exception generic){
//catch all
}catch(SpecificException se){
//catch specific exception only
}
What would happen when it comes across SpecificException ? Does it catch it as a generic exception first, and then catch the specificexception ?
Or does it only catch SpecificException while ignoring generic exceptions.
I don't want both generic and specificexception being caught.
This won't compile. You'll be told that the specific exception block isn't reachable.
You have to have the more specific exception catch block first, followed by the general one.
try
{
//something
}
catch(SpecificException se)
{
//catch specific exception only
}
catch(Exception generic)
{
//catch all
}
No. All exceptions would be caught by the first block. The second will never be reached (which the compiler recognizes, leading to an error due to unreachable code). If you want to treat SpecificException specifically, you have to do it the other way round:
}catch(SpecificException se){
//catch specific exception only
}catch(Exception generic){
//catch all
}
Then SpecificException will be caught by the first block, and all others by the second.
This does not compile with eclipse compiler:
Unreachable catch block for IOException. It is already handled by the catch block for Exception
So define them the other way. Only the specific one will be caught.
The catch blocks are tried in order, and the first one that matches the type of the exception is executed. Since Exception is the superclass of all exception types, it will always be executed in this instance and the specific cases will never be executed. In fact the compiler is smart enough to notice this and raise a compilation error.
Just reorder the catch clauses.
As a side note, the only way to have both catch blocks called is to use nested exceptions.
try {
try{
//something
}catch(SpecificException se){
//catch specific exception only
throw se;
}
}catch(Exception generic){
//catch all
}
My proposition - catch SQLException and check code.
try {
getConnectionSYS(dbConfigFile, properties);
} catch (SQLException e){
if (e.getErrorCode()==1017){
getConnectionUSER(dbConfigFile, properties);
} else {
throw e;
}
}

basic Java question: throwing an exception to a later catch clause?

If you have:
catch (FooException ex) {
throw new BarException (ex);
}
catch (BarException ex) {
System.out.println("hi");
}
...and the first catch clause is triggered (i.e. FooExcepetion has occurred),
does the new BarException get immediately caught by the subsequent "catch" clause?
Or is the new BarException thrown one level up the continuation stack?
I realize this is a basic question. : )
It does not get caught by the 2nd catch clause, no.
Each catch clause in the list is tried, to see if it matches. The first one that matches is the only one that runs, then the code moves on to the finally clause.
Another result of this is that if you have:
try {
throw SubTypeOfException(...);
} catch(Exception e) {
... block 1 ...
} catch(SubTypeOfException e) {
... block 2 ...
}
then block 1 is the only one that will run, even though block 2 would have matched. Only the first matching catch clause is evaluated.
It's thrown one level up.
You'll need another try//catch block.

Categories