Basically, I want to open a file, read some bytes, and then close the file. This is what I came up with:
try
{
InputStream inputStream = new BufferedInputStream(new FileInputStream(file));
try
{
// ...
inputStream.read(buffer);
// ...
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
try
{
inputStream.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
Maybe I’m spoiled by RAII, but there must be a better way to do this in Java, right?
If you have the same exception handling code for
IOExceptionandFileNotFoundExceptionthen you can rewrite your example in a more compact way with only onecatchclause:You can even get rid of the outer
try-catchif you can propagate the exception which probably makes more sense then manually printing the stack trace. If you don’t catch some exception in your program you’ll get stack trace printed for you automatically.Also the need to manually close the stream will be addressed in Java 7 with automatic resource management.
With automatic resource management and exception propagation the code reduces to the following: