Java Try Catch Finally blocks without Catch

144,243

Solution 1

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.

Solution 2

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).

Solution 3

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

Solution 4

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

Solution 5

The finally block is always run after the try block ends, whether try ends normally or abnormally due to an exception, er, throwable.

If an exception is thrown by any of the code within the try block, then the current method simply re-throws (or continues to throw) the same exception (after running the finally block).

If the finally block throws an exception / error / throwable, and there is already a pending throwable, it gets ugly. Quite frankly, I forget exactly what happens (so much for my certification years ago). I think both throwables get linked together, but there is some special voodoo you have to do (i.e. - a method call I would have to look up) to get the original problem before the "finally" barfed, er, threw up.

Incidentally, try/finally is a pretty common thing to do for resource management, since java has no destructors.

E.g. -

r = new LeakyThing();
try { useResource( r); }
finally { r.release(); }  // close, destroy, etc

"Finally", one more tip: if you do bother to put in a catch, either catch specific (expected) throwable subclasses, or just catch "Throwable", not "Exception", for a general catch-all error trap. Too many problems, such as reflection goofs, throw "Errors", rather than "Exceptions", and those will slip right by any "catch all" coded as:

catch ( Exception e) ...  // doesn't really catch *all*, eh?

do this instead:

catch ( Throwable t) ...
Share:
144,243
NullPointer0x00
Author by

NullPointer0x00

Updated on July 04, 2020

Comments

  • NullPointer0x00
    NullPointer0x00 almost 4 years

    I'm reviewing some new code. The program has a try and a finally block only. Since the catch block is excluded, how does the try block work if it encounters an exception or anything throwable? Does it just go directly to the finally block?

  • Andy Thomas
    Andy Thomas over 13 years
    First paragraph is not necessarily true. Try blocks can be nested. Any uncaught exception, unchecked or not, will bubble out of the method.
  • duffymo
    duffymo over 13 years
    Try blocks can be nested, but I wouldn't recommend it. I don't write code that way.
  • mplwork
    mplwork almost 11 years
    See answer by Carlos Heuberger below for the ugly part.
  • TodayILearned
    TodayILearned almost 9 years
    @duffymo: What is meaning of "bubbled out of the method"?
  • duffymo
    duffymo almost 9 years
    @Anand just some slightly non-technical language for "throwing an exception".
  • sbeliakov
    sbeliakov over 8 years
    What about try{..} catch{ throw ..} finally{..}? I think finally will not be executed
  • Vishy
    Vishy over 8 years
    In that case finally will still be called. Only the original exception is lost.
  • dahui
    dahui over 7 years
    Great answer, can anyone explain what "bubbled out of the method" means? It's ignored, or passed up the method chain?
  • duffymo
    duffymo over 7 years
    Not ignored; pass up the method chain.
  • Loduwijk
    Loduwijk about 7 years
    "before version 7 allow" are you implying that Java 7 and Java 8 do not allow these three combinations? I doubt that's what you mean, but that's what your answer implies.
  • mmirror
    mmirror about 7 years
    Finally will also not be executed if you call System.exit() before.
  • Vishy
    Vishy about 7 years
    @jyw That is what I meant by the first item in the list above.
  • Rahul Yadav
    Rahul Yadav almost 7 years
    is the finally block executed if there is a return statement in the try block?
  • roottraveller
    roottraveller almost 7 years
    @Rahul Yes, finally will be called. Ref : stackoverflow.com/questions/65035/…
  • Oscar Bravo
    Oscar Bravo about 6 years
    I have to say, this covers all the bases!
  • Roboprog
    Roboprog over 5 years
    @Aaron - new syntax for try-with-resource which automagically calls .close() on anything constructed within parens just after the try keyword.
  • Jin Thakur
    Jin Thakur over 3 years
    I have seen code with try catch after every line where input is getting collected.As almost every line can throws exception but process continues. For example so if registry not found give error message but read config file. Try database Connection so on. and one exception on top of method. It is sort of multi decision Process flow
  • duffymo
    duffymo over 3 years
    Ugly, unreadable boilerplate code. There are better ways to do such things.
  • user1500049
    user1500049 over 2 years
    Add a "return;" in the first "finally" block, result would print A,B,X,Z and no Y. Would anyone know why? Essentially this added "return" would mask out the Exception thrown?
  • Abdul kadir
    Abdul kadir over 2 years
    @Roboprog You're right, but the resource has to implement the Autocloseable interface