Practical-40
Write a java program which uses try and catch for Exception Handling.
1. Introduction
Exception handling is a mechanism which enables the programmer to handle abnormal program conditions and/or abnormal inputs. Java provides a robust and object-oriented approach to handle exceptions using the try-catch block. The basic idea behind using the try-catch block is to let the code execute in the try block until some abnormal condition is encountered and then handle the exception using the catch block code. In this programming task, we will implement a java program which uses try and catch for Exception Handling.
Code
public class TryCatch {
public static void main(String[] args) {
int x = 0;
try {
x = 1 / 0;
System.out.println ("The answer is: " + x);
} catch (ArithmeticException ae) {
System.out.println(ae);
}
}
}
Output
java.lang.ArithmeticException: / by zero
The program starts executing in the try block where we divide 1 by 0, which results in an ArithmeticException. When an exception is encountered, the program immediately stops executing the rest of the code in the try block and starts executing the code in the catch block. In this case, the catch statement prints the Exception which was encountered in the try block.