/**
* Question 1:
* Write a Java method called "divideByZero" that takes two integers, "numerator" and "denominator",
* as parameters and attempts to divide the numerator by the denominator. The method should use a try-catch block
* to catch any ArithmeticException that may occur if the denominator is zero.
* If a Division by zero occurs, the method should catch the exception, and print the message "Cannot divide by zero!".
* Otherwise, if the division is successful, the method should print the result of the division.
*
* You need to implement the "divideByZero" method.
*/
public class TryCatchExample {
public static void divideByZero(int numerator, int denominator) {
try {
int result = numerator / denominator;
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero!");
}
}
// Test case
public static void main(String[] args) {
// Test case 1: Division by zero
System.out.println("Test case 1:");
divideByZero(10, 0);
// Test case 2: Division without any exception
System.out.println("Test case 2:");
divideByZero(20, 5);
}
}
In this question, we need to write a Java method called "divideByZero" that takes two integers, numerator
and denominator
, as parameters and attempts to divide the numerator by the denominator. The method should use a try-catch block to catch any ArithmeticException
that may occur if the denominator is zero.
First, let's discuss the try-catch
block used in the divideByZero
method.
try {
int result = numerator / denominator;
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero!");
}
Inside the try
block, we perform the division operation by dividing the numerator
by the denominator
. If the division is successful (i.e., there is no division by zero), we print the result.
If a ArithmeticException
occurs (i.e., division by zero), the control flow jumps to the catch
block. Here, we catch the exception using ArithmeticException
as the parameter in the catch statement. Inside the catch block, we simply print the message "Cannot divide by zero!".
In the main
method, we have two test cases:
System.out.println("Test case 1:");
divideByZero(10, 0);
In test case 1, we try to divide 10 by 0. Since this is a division by zero scenario, the catch block will be executed, and the message "Cannot divide by zero!" will be printed.
System.out.println("Test case 2:");
divideByZero(20, 5);
In test case 2, we try to divide 20 by 5. This division is valid, and the result (4) will be printed.
The output of the program will be:
Test case 1:
Cannot divide by zero!
Test case 2:
Result: 4
This answers the requirements of the question, as it demonstrates the use of a try-catch block to handle a Division by zero exception.