Sometimes, the built-in error messages are not clear enough. Creating a custom exception class helps you give clear, specific error messages for your program.
Creating custom exception class in Java
Start learning this pattern below
Jump into concepts and practice - no test required
public class MyException extends Exception { public MyException(String message) { super(message); } }
You create a new class that extends Exception to make a checked exception.
The constructor passes the error message to the parent Exception class.
AgeException with a message.public class AgeException extends Exception { public AgeException(String message) { super(message); } }
RuntimeException.public class MyRuntimeException extends RuntimeException { public MyRuntimeException(String message) { super(message); } }
This program defines a custom exception AgeException. The checkAge method throws this exception if the age is less than 18. The main method calls checkAge with 16 and catches the exception to print the message.
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: " + age); } } public static void main(String[] args) { try { checkAge(16); } catch (AgeException e) { System.out.println("Caught exception: " + e.getMessage()); } } }
Custom exceptions help make your program errors easier to understand.
Checked exceptions (extending Exception) must be declared or caught.
Unchecked exceptions (extending RuntimeException) do not require declaration.
Create a new class that extends Exception or RuntimeException.
Use a constructor to pass a message to the parent class.
Throw your custom exception where needed and catch it to handle errors clearly.
Practice
Solution
Step 1: Understand Java exception hierarchy
Custom exceptions must extend eitherExceptionorRuntimeExceptionto behave like exceptions.Step 2: Recognize correct inheritance
Implementing an interface or naming a classExceptiondoes not create a proper exception class.Final Answer:
Extend the Exception or RuntimeException class -> Option AQuick Check:
Custom exception = extends Exception [OK]
- Trying to implement Exception as an interface
- Naming class Exception instead of extending it
- Using throw keyword in class declaration
MyException?Solution
Step 1: Identify correct constructor syntax
Constructors have no return type and callsuper(message)to pass the message to the parent Exception class.Step 2: Check each option
public MyException(String message) { super(message); } correctly defines a constructor callingsuper(message). public MyException() { this.message = message; } incorrectly assigns message without declaration. public void MyException(String message) { super(message); } has a void return type, so it's not a constructor. public MyException(String message) { print(message); } calls a non-existent methodprint.Final Answer:
public MyException(String message) { super(message); } -> Option CQuick Check:
Constructor calls super(message) = public MyException(String message) { super(message); } [OK]
- Adding void return type to constructor
- Not calling super(message) in constructor
- Trying to assign message directly without declaration
class MyException extends Exception {
public MyException(String message) {
super(message);
}
}
public class Test {
public static void main(String[] args) {
try {
throw new MyException("Error occurred");
} catch (MyException e) {
System.out.println(e.getMessage());
}
}
}Solution
Step 1: Understand exception throwing and catching
The code throws aMyExceptionwith message "Error occurred" and catches it immediately.Step 2: Check output from getMessage()
The catch block printse.getMessage(), which returns the message passed to the exception.Final Answer:
Error occurred -> Option AQuick Check:
Exception message printed = Error occurred [OK]
- Expecting class name instead of message
- Thinking code won't compile due to custom exception
- Missing try-catch block causing runtime error
public class MyException extends Exception {
public void MyException(String message) {
super(message);
}
}Solution
Step 1: Check constructor syntax
Constructors must not have a return type. Here,voidmakes it a method, not a constructor.Step 2: Understand consequences
Without a proper constructor, the class uses default constructor which does not callsuper(message), causing errors when throwing with message.Final Answer:
Constructor has a void return type, so it's a method, not a constructor -> Option DQuick Check:
Constructor no return type = Constructor has a void return type, so it's a method, not a constructor [OK]
- Adding void return type to constructor
- Assuming import Exception is needed
- Thinking super() cannot be called in subclass
InvalidDataException. Which is the correct way to define it?Solution
Step 1: Understand checked vs unchecked exceptions
Unchecked exceptions extendRuntimeException, checked exceptions extendException.Step 2: Analyze each option
public class InvalidDataException extends RuntimeException { public InvalidDataException(String message) { super(message); } } correctly extendsRuntimeExceptionwith proper constructor. public class InvalidDataException extends Exception { public InvalidDataException(String message) { super(message); } } creates a checked exception. public class InvalidDataException implements RuntimeException { public InvalidDataException(String message) { super(message); } } tries to implement an exception class, which is invalid. public class InvalidDataException extends Throwable { public InvalidDataException(String message) { super(message); } } extendsThrowabledirectly, which is not recommended for custom exceptions.Final Answer:
public class InvalidDataException extends RuntimeException { public InvalidDataException(String message) { super(message); } } -> Option BQuick Check:
Unchecked exception = extends RuntimeException [OK]
- Extending Exception for unchecked exceptions
- Trying to implement exception classes
- Extending Throwable directly
