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
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.