For Explanation 2, it says
"So, if IOException is thrown at line 1, the control goes to first catch which throws SQLException.
Now, although there is a catch for SQLException, it won't catch the exception because it is at the same level."
_________
Should this explanation be interpreted in the following manner:
The superclass of SQLException is
java.lang.Object
|
+----java.lang.Throwable
|
+----java.lang.Exception
|
+----java.sql.SQLException
Superclass is java.lang.Exception.
-----
java.lang.Exception is also the superclass of IOException.
Since IOException and SQLException are both subclasses of java.lang.Exception,
can one say that they are both at the same level?
Question: Is this how the sentence 2 in the explanation should be interpreted?
-----
Please confirm.
package oca;
import java.io.IOException;
import java.sql.SQLException;
public class ExceptionTest {
public static void main(String[] args) throws Exception{
m1();
}
@SuppressWarnings("finally")
public static void m1() throws Exception{
try{
throw new IOException();
}
catch(IOException e){
System.out.println("Catch IO Exception");
throw new SQLException();
}
catch(SQLException e){
System.out.println("Catch SQL Exception");
throw new InstantiationException();
}
finally{
System.out.println("Final block");
throw new CloneNotSupportedException();
}
}
}
This is what I try in Eclipse, but I receive
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Unreachable catch block for SQLException. This exception is never thrown from the try statement body
Please read my post above about the levels. You have a catch block for SQLException, but it can never be thrown by your try block. So the compiler realizes that the catch block for SQLException is useless here and therefore complains.
The code from the question is not compiling. If in the try block I throw an IOException, the catch(SQLException) line says that the exception is never thrown in body of corresponding try statement. If I throw an SQLExpception instead, then the catch(IOEXception) has the same compile error.
So this code will never compile in any case of the answers. How can any of the answers be correct then and reach the final clause?
class MyException extends Exception {}
public class TestClass{
public static void main(String[] args) throws Exception{
TestClass tc = new TestClass();
tc.m1();
}
void m1() throws Exception{
try{
throw new IOException(); //line 1
}
catch (IOException e){
throw new SQLException();
}
catch(SQLException e){
throw new InstantiationException();
}
finally{
throw new CloneNotSupportedException(); // this is not a RuntimeException.
}
}
Code for line 1 is not given. You have to assume that there is a valid line of code at that position that can potentially throw any exception that is referred to in the problem statement.
For example, you could have a call to method someMethod() that has throws IOException as well as SQLException in its throws clause.