Java Try Catch Finally blocks without Catch
If any of the code in the try block can throw a checked exception, it has to appear in the throws clause of the method signature. If an unchecked exception is thrown, it's bubbled out of the method.
The finally block is always executed, whether an exception is thrown or not.
A small note on try
/finally
: The finally will always execute unless
System.exit()
is called.- The JVM crashes.
- The
try{}
block never ends (e.g. endless loop).
The inner finally is executed prior to throwing the exception to the outer block.
public class TryCatchFinally {
public static void main(String[] args) throws Exception {
try{
System.out.println('A');
try{
System.out.println('B');
throw new Exception("threw exception in B");
}
finally
{
System.out.println('X');
}
//any code here in the first try block
//is unreachable if an exception occurs in the second try block
}
catch(Exception e)
{
System.out.println('Y');
}
finally
{
System.out.println('Z');
}
}
}
Results in
A
B
X
Y
Z
The Java Language Specification(1) describes how try-catch-finally
is executed.
Having no catch is equivalent to not having a catch able to catch the given Throwable.
- If execution of the try block completes abruptly because of a throw of a value V, then there is a choice:
- If the run-time type of V is assignable to the parameter of any catch clause of the try statement, then …
…- If the run-time type of V is not assignable to the parameter of any catch clause of the try statement, then the finally block is executed. Then there is a choice:
- If the finally block completes normally, then the try statement completes abruptly because of a throw of the value V.
- If the finally block completes abruptly for reason S, then the try statement completes abruptly for reason S (and the throw of value V is discarded and forgotten).
(1) Execution of try-catch-finally