Java Try Catch Finally blocks without Catch

后端 未结 11 814
没有蜡笔的小新
没有蜡笔的小新 2020-11-28 20:38

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

11条回答
  •  天命终不由人
    2020-11-28 21:09

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

提交回复
热议问题