throws Exception in finally blocks throws Exception in finally blocks java java

throws Exception in finally blocks


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 );  }}


I typically use one of the closeQuietly methods in org.apache.commons.io.IOUtils:

public static void closeQuietly(OutputStream output) {    try {        if (output != null) {            output.close();        }    } catch (IOException ioe) {        // ignore    }}


If you're using Java 7, and resource implements AutoClosable, you can do this (using InputStream as an example):

try (InputStream resource = getInputStream()) {  // Use the resource.}catch( Exception ex ) {  // Problem with the resource.}