Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

throws Exception in finally blocks

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?

like image 307
Paul Avatar asked Jan 26 '09 21:01

Paul


People also ask

What happens if we throw an exception in catch 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.

Will finally block gets executed after exception?

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.

Will the finally block be executed when the catch clause throws exception in Java?

The Finally Block A finally block of code always executes, irrespective of occurrence of an Exception.

How do I get exception message in finally block?

try { ..... throw new Exception("Exception Reason!"); } catch(Exception e){ msg=e. getMessage(); finally{ //USE String msg here. }


1 Answers

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 );   } } 
like image 99
Darron Avatar answered Oct 08 '22 20:10

Darron