Custom exceptions help you clearly show specific problems in your program. They make your code easier to understand and fix.
Why custom exceptions are needed in Java
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Syntax
Java
public class MyException extends Exception { public MyException(String message) { super(message); } }
Custom exceptions usually extend Exception or RuntimeException.
You can add your own messages or methods to give more details.
Examples
Java
public class AgeException extends Exception { public AgeException(String message) { super(message); } }
Java
public class InvalidInputException extends RuntimeException { public InvalidInputException(String message) { super(message); } }
Sample Program
This program defines a custom exception AgeException to check if age is at least 18. If not, it throws the exception. The main method catches it and prints the message.
Java
public class CustomExceptionDemo { static class AgeException extends Exception { public AgeException(String message) { super(message); } } public static void checkAge(int age) throws AgeException { if (age < 18) { throw new AgeException("Age must be at least 18."); } else { System.out.println("Age is valid."); } } public static void main(String[] args) { try { checkAge(16); } catch (AgeException e) { System.out.println("Caught custom exception: " + e.getMessage()); } } }
Important Notes
Custom exceptions improve code clarity by naming specific problems.
They help separate error handling for different cases.
Remember to document your custom exceptions so others understand when to use them.
Summary
Custom exceptions let you create clear, specific error messages.
They help your program handle different errors in different ways.
Using custom exceptions makes your code easier to read and maintain.
Practice
1. Why do we need custom exceptions in Java?
public class MyException extends Exception {}easy
Solution
Step 1: Understand the purpose of custom exceptions
Custom exceptions allow programmers to define errors that are specific to their application's needs, making error handling clearer.Step 2: Compare with other options
Replacing all built-in exceptions or avoiding try-catch blocks is not the goal. Custom exceptions do not improve speed directly.Final Answer:
To create specific error types that describe unique problems -> Option DQuick Check:
Custom exceptions = Specific error types [OK]
Hint: Custom exceptions describe unique problems clearly [OK]
Common Mistakes:
- Thinking custom exceptions speed up the program
- Believing they replace all built-in exceptions
- Assuming they remove the need for try-catch
2. Which of the following is the correct way to declare a custom checked exception in Java?
easy
Solution
Step 1: Identify checked exceptions
Checked exceptions in Java must extendExceptionbut notRuntimeException.Step 2: Analyze each option
ExtendingRuntimeExceptioncreates an unchecked exception. ExtendingErroris for system errors. ExtendingExceptioncreates a checked exception. ExtendingThrowableis too general.Final Answer:
class MyException extends Exception {} -> Option CQuick Check:
Checked exceptions extend Exception [OK]
Hint: Checked exceptions extend Exception class [OK]
Common Mistakes:
- Confusing checked and unchecked exceptions
- Extending Error instead of Exception
- Extending Throwable directly
3. What will be the output of this code?
class MyException extends Exception {}
public class Test {
public static void check(int num) throws MyException {
if (num < 0) throw new MyException();
else System.out.println("Number is " + num);
}
public static void main(String[] args) {
try {
check(-5);
} catch (MyException e) {
System.out.println("Caught MyException");
}
}
}medium
Solution
Step 1: Understand the check method behavior
If the number is less than 0, it throwsMyException. Since -5 < 0, exception is thrown.Step 2: Analyze main method's try-catch
The exception is caught in the catch block, which prints "Caught MyException".Final Answer:
Caught MyException -> Option AQuick Check:
Exception thrown and caught = "Caught MyException" [OK]
Hint: Exception thrown for negative, caught prints message [OK]
Common Mistakes:
- Expecting negative number print instead of exception
- Thinking code won't compile due to throws
- Missing catch block effect
4. Identify the error in this custom exception class:
public class MyException extends Exception {
public MyException(String message) {
super();
}
}medium
Solution
Step 1: Check constructor call to superclass
The constructor takes a message but callssuper()without passing it, so the message is lost.Step 2: Correct usage of super constructor
It should callsuper(message)to pass the error message to the Exception class.Final Answer:
Missing call to super(message) in constructor -> Option BQuick Check:
Pass message to super constructor [OK]
Hint: Pass message to super() in constructor [OK]
Common Mistakes:
- Calling super() without message
- Changing exception type unnecessarily
- Removing constructor parameters
5. You want to create a custom exception that handles invalid user input differently from other errors. Which approach best supports this goal?
hard
Solution
Step 1: Understand the need for specific error handling
To handle invalid input differently, a distinct exception type is needed.Step 2: Choose the best design
Creating a custom exception extending Exception allows catching it separately and handling it clearly.Final Answer:
Create a custom exception class extending Exception and catch it separately -> Option AQuick Check:
Custom exception + separate catch = clear handling [OK]
Hint: Custom exception + separate catch block for clarity [OK]
Common Mistakes:
- Using only built-in exceptions for all errors
- Throwing RuntimeException without clarity
- Avoiding exceptions and complicating code
