Java Custom exceptions

18-Sep-2024

Learn how to create and throw custom exceptions in Java for better error reporting.


In Java, You can create your own exception. This can achieve by Exception Class.


Custom exceptions:


1. A class that extends Exception.

2. Create Constructor to pass exception message.



class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
}


3. Throw your exceptions.



public class CustomExceptionExample {
public static void main(String[] args) {
try {
// This will throw CustomException
int age = 10;
if (age < 18) {
throw new CustomException("Age is not valid for voter.");
}
} catch (CustomException exception) {
System.out.println("CustomException caught: " + exception.getMessage());
}
}
}



In this example, we throw a custom exception if the age is less than 18.


Comments