The try-catch-finally Blocks in Java

man using desktop PC

Maskot / Getty Images

To make a Java program as robust as possible it needs to be able to handle exceptions. The compiler does its part by not allowing you to compile a program until it is syntactically correct and can also point out checked exceptions that must be handled. But the exceptions that are likely to cause the most headaches are the ones that appear once the program is running. To help handle these exceptions the Java language provides the try-catch-finally blocks.

The try Block

The

try
block encases any statements that might cause an exception to occur. For example, if you are reading data from a file using the
FileReader
class, it's expected that you handle the
IOExceptions
associated with using a
FileReader
object, for example,
FileNotFoundException
and
IOException
. To ensure this happens, you can place the statements that deal with creating and using the
FileReader
object inside a
try
block:However, the code is incomplete because, in order for the exception to be handled, we need a place for it to be caught. This happens in the

catch block.The catch Block

The

catch
block(s) provide a place to handle the exception thrown by the statements within a
try
block. The
catch
block is defined directly after the
try
block. It must specify the type of exception it is handling. For example, the
FileReader
object defined in the code above is capable of throwing a
FileNotFoundException
or an
IOException
. We can specify two
catch
blocks to handle both of those exceptions:In the
FileNotFoundExceptioncatch
block we could place code to ask the user to find the file for us and then try to read the file again. In the
IOException
catch block, we might just pass on the I/O error to the user and ask them to try something else. Either way, we have provided a way for the program to catch an exception and handle it in a controlled manner.
In Java SE 7, it became possible to handled multiple exceptions in one
catch
block. If the code we wanted to place in the two
catch
blocks above was exactly the same we could write the code like this instead:In order to do a bit of housekeeping as far as resources go, we can add a finally block. After all, we want to release the file we have been reading from once we are finished.

The finally Block

The statements in the finally block are always executed. This is useful to clean up resources in the event of the try block executing without an exception and in the cases when there is an exception. In both eventualities, we can close the file we have been using. 

The finally block appears directly after the last catch block: