-
There are three ways of handling a possible exception occurrence (we say that the exception is thrown). In some cases, such as when there is a possibility that a divide by zero exception might occur, the programmer has the option of not dealing with the exception at all. This can be useful in situations where the programmer has already taken steps to ensure that a denominator never becomes zero. The programmer may also attempt to fix the problem or skip over the problem. To do either of these, the programmer needs to catch any exception that may be thrown. To catch an exception, one must anticipate where the exception might occur and enclose that code in a try
block. The try block is followed by a catch
block that catches the exception (if it occurs) and performs the desired action.
The general form of a try-catch statement is:
try{
try-block
} catch (exception-type identifier){
catch-block
}
-
The try-block refers to a statement or series of statements that might throw an exception. If no exception is thrown, all of the statements within the try-block will be executed. Once an exception is thrown, however, all of the statements following the exception in the try-block will be skipped.
-
The catch-block refers to a statement or series of statements to be executed if the exception is thrown. A try block can be followed by more than one catch block. When an exception is thrown inside a try block, the first matching catch block will handle the exception.
-
exception-type specifies what kind of exception object the catch block should handle. This can be specific or it can be general, i.e. IOException or just Exception. Exception by itself will catch any type of exception that comes its way.
-
identifier is an arbitrary variable name used to refer to the exception-type object. Any operations done on the exception object or any methods called will use this identifier
The try
and catch
blocks work in a very similar manner to the if-else
statement and can be placed anywhere that normal code can be placed.
The value of denominator
is zero so an ArithmeticException
will be thrown whenever numerator
is divided by denominator
. The catch
block will catch the exception and print an error message. The println()
statement in the try
block will not be executed because the exception occurs before the program reaches that line of code. Once an exception is encountered, the rest of the lines of code in the try-block will be ignored. If the value of denominator
is not zero, the code in the catch
block will be ignored and the println()
statement will output the result of the division. Either way, the program continues executing at the next statement after the catch
block.