Challenge - 5 Problems
Custom Exception Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
π§ Conceptual
intermediatePurpose of Custom Exceptions in Java
Why do developers create custom exceptions instead of using only built-in exceptions?
Attempts:
2 left
π‘ Hint
Think about how custom exceptions help in understanding errors better.
β Incorrect
Custom exceptions allow programmers to signal specific problems related to their application's logic, making error handling clearer and more meaningful.
β Predict Output
intermediateOutput of Custom Exception Handling
What will be the output of this Java code?
Java
class MyException extends Exception { public MyException(String message) { super(message); } } public class Test { public static void check(int num) throws MyException { if (num < 0) { throw new MyException("Negative number not allowed"); } else { System.out.println("Number is " + num); } } public static void main(String[] args) { try { check(-5); } catch (MyException e) { System.out.println(e.getMessage()); } } }
Attempts:
2 left
π‘ Hint
Look at what happens when num is less than zero.
β Incorrect
The method throws a custom exception when the number is negative, which is caught and its message printed.
π§ Debug
advancedIdentify the Error in Custom Exception Usage
What error will this Java code produce when compiled?
Java
class MyException extends Exception { public MyException(String message) { super(message); } } public class Test { public static void check(int num) { if (num < 0) { throw new MyException("Negative number"); } } }
Attempts:
2 left
π‘ Hint
Check if the method declares the exception it throws.
β Incorrect
Since MyException extends Exception (checked exception), the method must declare it with 'throws' or handle it.
π Syntax
advancedCorrect Syntax to Define a Custom Exception
Which option shows the correct way to define a custom checked exception in Java?
Attempts:
2 left
π‘ Hint
Checked exceptions must extend Exception but not RuntimeException.
β Incorrect
Option D correctly extends Exception and calls the superclass constructor with a message.
π Application
expertCustom Exception Usage in Application Logic
Given this scenario: You want to signal a specific error when a user tries to withdraw more money than their account balance. Which custom exception usage is best to handle this?
Attempts:
2 left
π‘ Hint
Think about clarity and forcing the caller to handle the error.
β Incorrect
A custom checked exception clearly signals the specific problem and forces handling, improving code safety and readability.
