Question

I wonder why for example in the following snippet:

try{
   //here happens a SQLException
}
catch(SQLException e){
   throw new InstantiationException();
}
finally{
   System.out.println("This is the finally");
}

The outcome of this bit of code will be printing out "This is the finally" first and only after it prints out InstantiationException ...

Was it helpful?

Solution

From Java Language Specification::

If execution of the try block completes abruptly because of a throw of a value V, then there is a choice: (SQLException throw in try clause)

If the run-time type of V is assignment compatible with a catchable exception class of any catch clause of the try statement, then the first (leftmost) such catch clause is selected. The value V is assigned to the parameter of the selected catch clause, and the Block of that catch clause is executed. Then there is a choice:

If the catch block completes normally, then the finally block is executed. Then there is a choice:

If the finally block completes normally, then the try statement completes normally.

If the finally block completes abruptly for any reason, then the try statement completes abruptly for the same reason.

If the catch block completes abruptly for reason R, then the finally block is executed. Then there is a choice: (InstantiationException throw)

If the finally block completes normally, then the try statement completes abruptly for reason R.(System.out.println("This is the finally"))

I have put text in bold each execution step.

To Summarize:

  1. An SQLException is thrown in your try block
  2. control transferred to Catch clause which handles SQLException
  3. Catch clause is abruptly completed as you throw InstantiationException
  4. finally block is executed by printing your text
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top