display | more...
The try/catch/finally statement is used in Java to handle Exceptions and abnormal exits. It consists of three blocks: try, catch and finally.

Here I will attempt to demonstrate its most common use, in catching and handling exceptions...

public void rooExample() {
   try {
      // in this try block we're going to call a method
      // which might throw SomeWeirdException.
   catch (SomeWeirdException e1) {
      // If the exception was caught
      System.out.println("ARGH! This exception was thrown... " + e1);
Zero or more catch blocks can be used to catch different exceptions within the same code. If the specified exception is thrown in the try block, execution is halted and control is passed to the start of the relevant catch block.

Exceptions can be subclassed, and a catch block handles the specified exception and any subclasses of that exception. Thus, it is common to see

catch (Exception e)
Finally, the finally block. This is optional. It's so optional in fact that I have known many seasoned Java developers who didn't know why it was useful.

The finally block is guaranteed to be executed. "So what?", some people ask, "The code after the try/catch/finally statement is going to execute anyway!"

Well, if the try block contains something which would transfer control such as return, break or continue, then the code may not reach the next line after the try/catch/finally statement all. By using a finally block, you can ensure that your important clean-up code is executed regardless of how the try block finished.

Log in or register to write something here or to contact authors.