Home | FAQ | Contact me

Java try-catch-finally

The usual, pre-Java 1.7 wiggle:

private void foo( URL url )
{
  InputStream input = null;

  try
  {
    input = url.openStream();
    // reads the stream, throws IOException
  }
  catch( IOException ex )
  {
    throw new RuntimeException( ex );
  }
  finally
  {
    if( input != null )
      input.close();
  }
}

Better—and let's avoid the whole null nightmare:

private void foo( URL url ) throws IOException
{
  final InputStream input = url.openStream();

  try
  {
    // reads the stream, throws IOException
  }
  catch( IOException ex )
  {
    throw new RuntimeException( ex );
  }
  finally
  {
    input.close();
  }
}

If opening the resource also throws an exception:

private void foo( URL url )
{
  final InputStream input;

  try
  {
    input = url.openStream();
  }
  catch( IOException ex )
  {
    throw new RuntimeException( ex );
  }
  try
  {
    // reads the stream, throws IOException
  }
  catch( IOException ex )
  {
    throw new RuntimeException( ex );
  }
  finally
  {
    input.close();
  }
}