How to Create Custom Exception in Java: Simple Guide
To create a custom exception in Java, define a new class that extends
Exception or RuntimeException. Then, add constructors to pass error messages or causes to the parent class.Syntax
To create a custom exception, you define a class that extends Exception for checked exceptions or RuntimeException for unchecked exceptions. You usually add constructors to pass messages or causes.
- class YourException extends Exception: Defines a checked exception.
- class YourException extends RuntimeException: Defines an unchecked exception.
- Constructors call
super()to set error messages.
java
public class MyCustomException extends Exception { public MyCustomException(String message) { super(message); } public MyCustomException(String message, Throwable cause) { super(message, cause); } }
Example
This example shows how to create and use a custom checked exception called InvalidAgeException. It is thrown when an age is less than 18.
java
class InvalidAgeException extends Exception { public InvalidAgeException(String message) { super(message); } } public class TestCustomException { public static void checkAge(int age) throws InvalidAgeException { if (age < 18) { throw new InvalidAgeException("Age must be at least 18"); } else { System.out.println("Age is valid: " + age); } } public static void main(String[] args) { try { checkAge(15); } catch (InvalidAgeException e) { System.out.println("Caught exception: " + e.getMessage()); } } }
Output
Caught exception: Age must be at least 18
Common Pitfalls
- For checked exceptions, always declare them with
throwsin method signatures. - Do not forget to call
super(message)in constructors to set the error message. - Use
RuntimeExceptionfor unchecked exceptions if you want to avoid mandatorytry-catch. - Do not catch your custom exception unless you can handle it properly.
java
/* Wrong: Missing super call and no constructors */ class BadException extends Exception { } /* Right: Proper constructors with super calls */ class GoodException extends Exception { public GoodException(String message) { super(message); } }
Quick Reference
- Extend
Exceptionfor checked exceptions. - Extend
RuntimeExceptionfor unchecked exceptions. - Always provide constructors that call
super(). - Throw your custom exception with
throw new YourException("message"). - Declare checked exceptions with
throwsin method signatures.
Key Takeaways
Create a custom exception by extending Exception or RuntimeException.
Always call super() in constructors to set error messages.
Declare checked exceptions with throws in method signatures.
Use RuntimeException for unchecked exceptions to avoid mandatory catching.
Throw your custom exception with throw new YourException("message").