Consider the following code snippet:
public class MathUtils {
public static double divide(double numerator, double denominator) {
if (denominator == 0) {
throw new ArithmeticException("Division by zero is not allowed");
}
return numerator / denominator;
}
public static int calculateFactorial(int n) {
if (n < 0) {
throw new IllegalArgumentException("Factorial is not defined for negative numbers");
}
int factorial = 1;
for (int i = 2; i <= n; i++) {
factorial *= i;
}
return factorial;
}
public static void main(String[] args) {
try {
double result = divide(10, 0);
int factorial = calculateFactorial(-5);
} catch (ArithmeticException e) {
System.out.println("ArithmeticException: " + e.getMessage());
} catch (IllegalArgumentException e) {
System.out.println("IllegalArgumentException: " + e.getMessage());
}
}
}
divide
method and calculateFactorial
method.try-catch
block of the main
method.divide
method and calculateFactorial
method is to handle exceptional scenarios or error conditions.In the divide
method, throwing an ArithmeticException
with the message "Division by zero is not allowed" ensures that the code stops executing and an exception is thrown when the denominator is zero. This prevents a division by zero error, which is an invalid operation in mathematics.
In the calculateFactorial
method, throwing an IllegalArgumentException
with the message "Factorial is not defined for negative numbers" ensures that the code stops executing and an exception is thrown when a negative number is passed as the argument. This prevents calculating the factorial of a negative number, which is not defined mathematically.
try-catch
block in the main
method is used to handle the exceptions thrown by calling the divide
and calculateFactorial
methods.Without the try-catch
block, if an exception is thrown, the program would terminate abruptly, and the exception would not be handled gracefully. By using the try-catch
block, the program can catch specific exceptions and handle them appropriately.
ArithmeticException: Division by zero is not allowed
IllegalArgumentException: Factorial is not defined for negative numbers
The first line "ArithmeticException: Division by zero is not allowed" is printed because the divide
method throws an ArithmeticException
when the denominator is zero. In this case, the exception is caught in the catch
block of the main
method and the error message is printed.
The second line "IllegalArgumentException: Factorial is not defined for negative numbers" is printed because the calculateFactorial
method throws an IllegalArgumentException
when a negative number is passed. In this case, the exception is caught in the catch
block of the main
method and the error message is printed.
Both exceptions occur due to invalid input values and are handled using the appropriate catch
blocks.