Learn how to create custom exceptions in Java by extending Exception or RuntimeException, throw them, and handle them to implement robust business logic and error handling.
Custom Exceptions in Java – Complete Detailed Tutorial
Sometimes, built-in exceptions are not enough for your application.
Java allows creating custom exceptions for specific business logic or application rules.
1. Creating a Custom Exception
- Extend
Exception→ for checked exceptions (must be handled) - Extend
RuntimeException→ for unchecked exceptions (optional handling)
Syntax:
class MyException extends Exception {
MyException(String message) {
super(message);
}
}
2. Example – Checked Custom Exception
class AgeException extends Exception {
AgeException(String message) {
super(message);
}
}
class Test {
void checkAge(int age) throws AgeException {
if (age < 18) {
throw new AgeException("Age must be 18 or older");
} else {
System.out.println("Access granted");
}
}
}
public class Main {
public static void main(String[] args) {
Test t = new Test();
try {
t.checkAge(15);
} catch (AgeException e) {
System.out.println("Custom Exception caught: " + e.getMessage());
}
}
}
Output:
Custom Exception caught: Age must be 18 or older
3. Example – Unchecked Custom Exception
class NegativeNumberException extends RuntimeException {
NegativeNumberException(String message) {
super(message);
}
}
public class Main {
static void checkNumber(int num) {
if (num < 0) {
throw new NegativeNumberException("Negative numbers are not allowed");
} else {
System.out.println("Number is valid: " + num);
}
}
public static void main(String[] args) {
checkNumber(-5);
}
}
Output:
Exception in thread "main" NegativeNumberException: Negative numbers are not allowed
Explanation:
- Unchecked exceptions do not require try-catch
- Program may terminate if unhandled
4. Advantages of Custom Exceptions
- Represent application-specific errors
- Improve readability and maintainability
- Allow more precise exception handling
- Useful in business logic validation
5. Key Points
- Checked custom exceptions: extend
Exception, must be caught or declared - Unchecked custom exceptions: extend
RuntimeException, optional handling - Use
super(message)to pass custom error message - Helps create meaningful exception messages