Java: Try, Catch, Finally Statement


I wrote the summary about try, catch and finally statement in Java.

Overview and simple format

try .. catch statement can capture exceptions thrown in the program. Simple try .. catch statement must be written in the following form. In that form, when an exception is thrown in the statements 1, then the program goes to catch block and check whether the type of the error is ErrorOrExceptionType. If yes, then statement 2 is executed, otherwise the program is interrupted and stopped. In statements 2, the error information can be used with the variable ex, which was defined in the parenthesis just after catch.

Format

Example

Here is an example. This example reads from characters from standard input as int and divide 100 by it.

Especially, when we write catch (Exception e), we can handle any exception and we don’t have to check all the condition such as the file existence and permission when we use files for example. But catching Exception is not always effective, because in the product, we have to pay attention to what kind of message must be sent to users according to the error or exception types. In those cases, multiple catch blocks make sense.

Multiple catch blocks

try .. catch statement can include multiple catch blocks as follows. In that form, the exception is compared to ErrorOrExceptionType1 first, and if they are not the same, the error is compared to the following ErrorOrExceptionTypes, step by step from up to down. When the exception type is the same as one ErrorOrExceptionType, the statements in its catch block are executed. Once the exception is caught, its following catch block is not executed.

Format

Example

This example reads from characters from standard input, converts it to int and divide 100 by it.

When we use a database, sometimes SQLException is thrown according to the database status. SQLException class has some methods which are not in Exception class, such as getSQLState, getErrorCode. Catching SQLException is meaningful to know more information about the database and its connection. So catching SQLException at first is meaningful.

Finally block

A finally block can be added after catch block as follows. finally block is executed after try and catch block regardless of error existence.

Format

Example

In this example, “finished.” is always printed out.