Exception handling in Java is an effective mechanism for managing runtime errors to ensure the application's regular flow is maintained. Some Common examples of exceptions include ClassNotFoundException, IOException, SQLException, RemoteException, etc. By handling these exceptions, Java enables developers to create robust and fault-tolerant applications.
Example: Showing an arithmetic exception or we can say a divide by zero exception.
import java.io.*;
class Geeks {
public static void main(String[] args)
{
int n = 10;
int m = 0;
int ans = n / m;
System.out.println("Answer: " + ans);
}
}
Note :
When an exception occurs and is not handled, the program terminates abruptly and the code after it, will never execute.
example:
The below Java program modifies the previous example to handle an ArithmeticException using try-catch and finally blocks and keeps the program running.
import java.io.*;
class Geeks {
public static void main(String[] args)
{
int n = 10;
int m = 0;
try {
// Code that may throw an exception
int ans = n / m;
System.out.println("Answer: " + ans);
}
catch (ArithmeticException e) {
// Handling the exception
System.out.println(
"Error: Division by zero is not allowed!");
}
finally {
System.out.println(
"Program continues after handling the exception.");
}
}
}
output:
Error: Division by zero is not allowed!
Program continues after handling the exception.
Java Exception Hierarchy:
Java, all exceptions and errors are subclasses of the Throwable class. It has two main branches
Exception.
Error
The below figure demonstrates the exception hierarchy in Java:
Exception Hierarchy in Java
Heirarchy of
Major Reasons Why an Exception Occurs.
Exceptions can occur due to several reasons, such as:
Invalid user input
Device failure
Loss of network connection
Physical limitations (out-of-disk memory)
Code errors
Out of bound
Null reference
Type mismatch
Opening an unavailable file
Database errors
Arithmetic errors
Errors are usually beyond the control of the programmer and we should not try to handle errors.
Nested try-catch:
In Java, you can place one try-catch block inside another to handle exceptions at multiple levels.
public class NestedTryExample {
public static void main(String[] args) {
try {
System.out.println("Outer try block");
try {
int a = 10 / 0; // This causes ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Inner catch: " + e);
}
String str = null;
System.out.println(str.length()); // This causes NullPointerException
} catch (NullPointerException e) {
System.out.println("Outer catch: " + e);
}
}
}
Top comments (0)