You are given the following Java code:
public class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
}
public class ExceptionTester {
public void testMethod(int num) throws CustomException {
if (num < 0) {
throw new CustomException("Number must be positive");
} else if (num > 100) {
throw new CustomException("Number must be less than or equal to 100");
}
}
public static void main(String[] args) throws CustomException {
ExceptionTester tester = new ExceptionTester();
try {
tester.testMethod(-5);
tester.testMethod(500);
tester.testMethod(50);
} catch (CustomException e) {
System.out.println(e.getMessage());
}
}
}
Explain the output of the above code when executed.
The output of the above code when executed will be:
Number must be positive
Number must be less than or equal to 100
Explanation:
The ExceptionTester
class defines a method testMethod
that takes an integer num
as a parameter and throws a CustomException
depending on the value of num
. If num
is less than 0, the method throws a CustomException
with the message "Number must be positive". If num
is greater than 100, the method throws a CustomException
with the message "Number must be less than or equal to 100".
In the main
method, an instance of ExceptionTester
is created. Then, the testMethod
is called three times with different values: -5, 500, and 50. Each of these calls is wrapped inside a try-catch block where the catch block catches the CustomException
and prints its message using e.getMessage()
.
When the testMethod
is called with -5 as the argument, it throws a CustomException
with the message "Number must be positive". This exception is caught by the first catch block, and the message "Number must be positive" is printed.
Next, when the testMethod
is called with 500 as the argument, it throws a CustomException
with the message "Number must be less than or equal to 100". This exception is caught by the second catch block, and the message "Number must be less than or equal to 100" is printed.
Finally, when the testMethod
is called with 50 as the argument, no exception is thrown. Hence, nothing is printed for this call.
Therefore, the output of the code is:
Number must be positive
Number must be less than or equal to 100