Java provides specific exception classes for common exceptional situations. Some of the commonly used specific exception classes in Java are:
ArithmeticException
: This exception is thrown when an arithmetic operation fails. For example, dividing a number by zero.NullPointerException
: This exception is thrown when a null reference is used where an object is required.ArrayIndexOutOfBoundsException
: This exception is thrown when an invalid index is used to access an array.
To handle specific exceptions in Java, you can use the try-catch
statements. The try
block contains the code that may throw an exception, and the catch
block is used to handle the specific exception.
In the example code provided, we have a divide
method that divides two integers. If the divisor is zero, it throws an ArithmeticException
with the message "Division by zero is not allowed." In the main
method, we attempt to divide 10 by 0 and catch the ArithmeticException
to handle the exception. The error message is then printed to the console.
When running the code, you will see the output:
1An arithmetic exception occurred: Division by zero is not allowed.
xxxxxxxxxx
class Main {
public static void main(String[] args) {
try {
int result = divide(10, 0);
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("An arithmetic exception occurred: " + e.getMessage());
}
}
public static int divide(int dividend, int divisor) throws ArithmeticException {
if (divisor == 0) {
throw new ArithmeticException("Division by zero is not allowed.");
}
return dividend / divisor;
}
}