Consider the following code snippet:
public class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
}
public class ExceptionThrower {
public static void main(String[] args) {
try {
throwCustomException();
} catch (CustomException e) {
System.out.println(e.getMessage());
} catch (Exception e) {
System.out.println("Unhandled Exception");
}
}
public static void throwCustomException() throws CustomException {
int randomNum = (int) (Math.random() * 10);
if (randomNum >= 5) {
throw new CustomException("Random number is greater than or equal to 5");
}
}
}
Explain what is happening in the code snippet above and what will be the output when it is executed. If any exceptions are thrown, clearly state which exception will be caught by each catch
block and the corresponding output.
The code above provides an example of throwing a custom exception and catching it using a try-catch block. The CustomException
class is a custom exception that inherits from the built-in Exception
class.
In the main
method, the throwCustomException
method is called within a try block. Inside the throwCustomException
method, a random number between 0 and 9 (inclusive) is generated. If the random number is greater than or equal to 5, the method throws a CustomException
with the message "Random number is greater than or equal to 5".
Since the throwCustomException
method specifies that it can throw a CustomException
, the main
method catches it using a catch block specific to CustomException
. If the CustomException
is caught, the message of the exception is printed. If any other exception is thrown, such as a general Exception
, it is caught by the second catch block, which prints "Unhandled Exception".
When the code is executed, there are two possible outputs based on the generated random number:
If the random number is less than 5:
If the random number is greater than or equal to 5:
throwCustomException
method throws a CustomException
with the message "Random number is greater than or equal to 5"catch
block for CustomException
catches the exception and prints the message "Random number is greater than or equal to 5"Therefore, the expected output when the code is executed depends on the randomly generated number.