There are three ways of handling a possible exception occurrence (we say that the exception is thrown).
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.
If an exception is thrown anywhere in the try block which matches one of the exception-types named in a catch block, then the code in the appropriate 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:
int quotient;
int numerator = 23;
int denominator = 0;
try{
quotient = numerator/denominator;
System.out.println("The answer is: " + quotient);
} catch (ArithmeticException e){
System.out.println("Error: Division by zero");
}
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. 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. 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.Last modified: December 12, 2022
Back to Exceptions