| | |
| Handling Exceptions | page 4 of 8 |
When a exception occurs (we say that the exception is thrown), the program has the option of catching it. To catch an exception, we 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
}
catch (exception-type identifier)
{
catch-block
}
- The try-block refers to a statement or series of statements that might throw an exception.
- 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.
- identifier is an arbitrary variable name used to refer to the exception-type object.
The try and catch blocks together form a single statement, which can be used anywhere in a program that a single statement is allowed.
If an exception is thrown anywhere in the try block, and the exception matches the one named in the catch block, then the code in the catch block is executed. If the try block executes normally, without an exception, the catch block is ignored.
Here is an example of try and catch:
import chn.util.*;
public class CheckDivideByZero
{
public static void main (String[] args)
{
ConsoleIO console = new ConsoleIO();
int quotient;
System.out.print("Enter the numerator: ");
int numerator = console.readInt();
System.out.print("Enter the denominator: ");
int denominator = console.readInt();
try
{
quotient = numerator/denominator;
System.out.println("The answer is: " + quotient);
}
catch (ArithmeticException e)
{
System.out.println("Error: Division by zero");
}
}
}
Run Output:
Enter the numerator: 23
Enter the denominator: 0
Error: Division by zero
If the value of denominator is zero, then an ArithmeticException will be thrown when numerator is divided by denominator. The catch block will catch the exception and print an error message. If the value of denominator is not zero, the code in the catch block will be ignored. Either way, the program continues executing at the next statement after the catch block.
|