Exception Handling
Exceptions are the run-time errors that can be caught and handled by the programmers to avoid termination of program execution. The statements which may cause a run-time error are written inside the try block and the statements which are to be executed when an error is encountered are placed inside the catch block. A try block can be followed by more than one catch block or a finally block. The statements inside the finally block will be executed either if there is an error or no error in the program. The following program explains how to write try and catch blocks to handle exceptions. If more than one catch block follows the try block, then the catch blocks must be placed in the reverse order of the order in which the exceptions are inherited. All the exceptions both pre-defined and user-defined are the derived class of the base class Exception.
Program
OUTPUT
Enter two numbers
10
2
Division result = 5
D:\Java\19csc>java TryCatch
Enter two numbers
10
0
Divide by zero error java.lang.ArithmeticException: / by zero