import java.util.Scanner;
import static java.lang.System.out;
public class practice
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int x=sc.nextInt();
try //outer try
{
try //inner try
{
if(x==1)
throw new NullPointerException();
else if(x==2)
throw new InterruptedException();
else
throw new RuntimeException();
}
catch(RuntimeException e) //catch block 1
{
out.println("RuntimeException caught!");
}
catch(InterruptedException e) //catch block 2
{
out.println("InterruptedException caught!");
}
out.println("inner try ends");
return;
}
catch(Exception e) //catch block 3
{
out.println("Exception caught!");
}
finally
{
out.println("from finally");
}
out.println("main ends"); //unreachable code?
}
}
In the above code, an exception is always thrown from the inner try block.
It is either a RuntimeException (unchecked Exception) or an InterruptedException (checked Exception) that is caught by catch block 1
or catch block 2
.
Any unchecked exception generated (not predicted by the compiler) will however be caught by catch block 1
. As a result, the catch block 3
never gets executed.
Moreover, the line out.println("main ends");
also never gets executed due to the return
statement in the outer try
block.
My interpretation is wrong, since the program compiled successfully.
Can someone please tell me when does catch block 1
or the line out.println("main ends");
get executed?