Is there an elegant way to handle exceptions that are thrown in finally
block?
For example:
try { // Use the resource. } catch( Exception ex ) { // Problem with the resource. } finally { try{ resource.close(); } catch( Exception ex ) { // Could not close the resource? } }
How do you avoid the try
/catch
in the finally
block?
If an exception occurs in the try block, the catch block (or blocks) that follows the try is verified. If the type of exception that occurred is listed in a catch block, the exception is passed to the catch block much as an argument is passed into a method parameter.
Yes, the finally block will be executed even after a return statement in a method. The finally block will always execute even an exception occurred or not in Java.
The Finally Block A finally block of code always executes, irrespective of occurrence of an Exception.
try { ..... throw new Exception("Exception Reason!"); } catch(Exception e){ msg=e. getMessage(); finally{ //USE String msg here. }
I usually do it like this:
try { // Use the resource. } catch( Exception ex ) { // Problem with the resource. } finally { // Put away the resource. closeQuietly( resource ); }
Elsewhere:
protected void closeQuietly( Resource resource ) { try { if (resource != null) { resource.close(); } } catch( Exception ex ) { log( "Exception during Resource.close()", ex ); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With