Challenge - 5 Problems
Custom Exception Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
β Predict Output
intermediateOutput of custom exception message
What is the output of this Java program that uses a custom exception class?
Java
class MyException extends Exception { public MyException(String message) { super(message); } } public class Test { public static void main(String[] args) { try { throw new MyException("Custom error occurred"); } catch (MyException e) { System.out.println(e.getMessage()); } } }
Attempts:
2 left
π‘ Hint
Look at what getMessage() returns from the Exception class.
β Incorrect
The getMessage() method returns only the message string passed to the exception, so it prints exactly "Custom error occurred".
β Predict Output
intermediateValue of variable after catching custom exception
What is the value of variable 'result' after running this code?
Java
class MyException extends Exception {} public class Test { public static int testMethod() throws MyException { throw new MyException(); } public static void main(String[] args) { int result = 0; try { result = testMethod(); } catch (MyException e) { result = -1; } System.out.println(result); } }
Attempts:
2 left
π‘ Hint
Consider what happens when the exception is thrown and caught.
β Incorrect
The method throws MyException, so the try block does not assign to result. The catch block assigns -1 to result, which is printed.
π Syntax
advancedIdentify syntax error in custom exception class
Which option contains a syntax error in defining a custom exception class?
Attempts:
2 left
π‘ Hint
Check how the superclass Exception stores the message.
β Incorrect
Option D tries to assign to 'this.message' which is not accessible; the correct way is to call super(message).
π§ Conceptual
advancedPurpose of creating a custom exception class
Why would a developer create a custom exception class instead of using existing Java exceptions?
Attempts:
2 left
π‘ Hint
Think about how exceptions help communicate problems.
β Incorrect
Custom exceptions help clearly indicate specific problems related to the application's logic or domain, making error handling clearer.
π§ Debug
expertWhy does this custom exception code fail to compile?
This code tries to define a custom checked exception but fails to compile. What is the cause?
Java
class MyException extends Exception { public MyException() { System.out.println("Error"); } } public class Test { public static void main(String[] args) { throw new MyException(); } }
Attempts:
2 left
π‘ Hint
Check the method main's throws declaration and checked exceptions rules.
β Incorrect
MyException extends Exception, which is checked. The main method does not declare throws MyException, so throwing it causes a compile error.
