The try Statement

The try statement is used wherever there is code that could throw an exception. It involves the use of three reserved words: try, catch and finally. The syntax is the following:

The try statement must contain at least one catch block or one finally block.

The catch Block

The three things you must know about the catch block for the exam are:

  • The caught exception type must inherit from Throwable
  • JVM invokes the first exception handler in the call stack whose exception type matches the type of the exception thrown (matches = the thrown object can legally be assigned to the exception handler’s argument)
  • If there are several handlers in same level, they are checked in the order in which they appear after the try statement

The Multi-Catch Block

Since Java version 7 it’s possible to catch more than one exception type with just one handler. The syntax is the following:

The restrictions are:

  • Variable e is implicitly final
  • In the same multi-catch block you cannot include different exception classes that are related by inheritance (e.g. IndexOutOfBoundException and ArrayIndexOutOfBoundException)

The finally Block

The finally block avoids bypassing cleanup code accidentally or duplicating it in the try and catch blocks.  The two things you must know about the finally block for the exam are:

  • It always executes when the try block exits, even with continue, break throw or return.  The only exceptions are: System.exit() and JVM or thread exit
  • It can exist without the catch block

Nesting Things

You can use new try-catch blocks inside the catch and finally blocks.

You can also throw exceptions from the catch and finally blocks, but remember:

  • The exception that is thrown the last is the one that is thrown out by the method
  • Exceptions thrown from a catch block cannot be caught by the next catch blocks at the same level

Throwing Exceptions from the main Method

Although you could think of the main method of a program as the lowest level in the call stack (and so there are no handlers under it to catch exceptions), it can also declare that it throws any kind of exception.

If an exception is thrown out of the main method then it is handled by the JVM’s uncaught exception handling mechanism, which prints the stack trace and terminates the program.

Speaking about printing exceptions… do you know the difference between the following two sentences?

  1. System.out.println(exception);
  2. exception.printStackTrace();

If you don’t, you should:

  • The first one prints just the name of the exception class and the associated message (if it exists)

  • The second one prints the chain of the names of the methods called, along with the line numbers, from the point where the exception was thrown and up to the point where the exception was caught, e.g.:

Leave a Reply