Exception Handling Program in Java
Exception means something that is abnormal. In Java, an exception is treated as a problem that disrupts the normal flow of the program. An exception leads to abnormal termination of the Java program. There can be many scenarios where an exception can occur. A few of them are mentioned below.
- When a number is divided by zero, for example, int x = 6 / 0; This statement is syntactically correct, but zero can never divide a number mathematically. Hence, an exception is raised.
- Connecting to a server, but the server is off.
- Opening a file, but the file is already deleted by someone.
- Accessing the index that is not present in the array.
For example, in the statement int arr[] = {7, 8, 9};, the array contains three elements arr[0], arr[1], arr[2], but if someone tries to access arr[10], then it is not possible as 10th index is not present in the array leading to the generation of an exception. - When JVM has run out of memory.
- User is entering some invalid data. For example, someone types 1342 when asked to write his/ her name.
Some of the exception scenarios mentioned above are due to programmer error; some are due to failure of the resources, while others are due to user error.The exception handling program in Java demonstrates how to handle exceptions in order to maintain the natural flow of the program.
Hierarchical Structure of Exception in Java
All classes of exception are derived from the class java.lang.Exception, while the Exception class itself is the child class of the class Throwable. Errors are also the subtypes of the class Throwable.
The need of handling an Exception
Suppose there are 8 statements in a Java program, and an exception has occurred at the 4th statement. Due to exception, the normal flow of the program is interrupted that leads to abnormal termination of the program. Thus, the statements that are coming after the 4th statement never get executed. To ensure that statements after the 4th statement are executed, or to ensure the normal flow of the program, it is required to handle the exception that is raised due to the 4th statement.
Types of Exception in Java
Exceptions in Java can be categorized into the following three categories:
1) Checked Exception
2) Unchecked Exception
3) Error