Control Flow  «Prev  Next»


Lesson 7The try-catch Statement
Objective Describe how Exceptions are caught

try-catch statement in Java

Exceptions are caught using the try-catch statement. The try part of the statement surrounds the statements for which exceptions are to be caught, and the catch part identifies the exception class that is caught and how the exception is to be processed. Multiple catch clauses may be used. An optional finally clause identifies processing that is to be performed whether or not an exception is thrown or caught. Only one finally clause may be used. The catch clause declares a variable that identifies the type of exceptions that it catches. The type of this variable may be any class that extends Throwable. The catch clause catches any exceptions that are subclasses of this type. If multiple catch clauses are supplied, the first matching catch clause is executed. Subsequent catch clauses are ignored. The finally clause identifies code that is to be executed after the catch clause (if any) or the try statement.


Java try-catch Statement

1) An abnormal condition in the normal flow of execution causes an exception to be thrown.
1) An abnormal condition in the normal flow of execution causes an exception to be thrown.

2) Is the exception assignable to Exception 1.
2) Is the exception assignable to Exception 1. If it is, that catch clause is executed. If it is not, send it to the next catch clause.

3) Is the exception assignable to Exception 2.
3) Is the exception assignable to Exception 2. If it is, that catch clause is executed. If it is not, send it to the finally clause.


4) The finally clause is always executed, even if an exception is thrown and not caught.
4) The finally clause is always executed, even if an exception is thrown and not caught. Uncaught exceptions are propogated after execution of the finally clause


Java Virtual Machine
Java - try catch - statement
Multiple try-catch statements may be nested within each other. The nested try-catch statement is contained in the try clause of the try-catch statement in which it is nested.

try catch - Quiz

Click the Quiz link below to check your understanding of switch statements, loop execution, and Exception handling.
try catch - Quiz