A custom exception is a user-defined exception in Java. You can create custom exceptions to handle specific errors or exceptional situations that may occur in your application. This is useful when you want to catch and handle errors in a specific way, rather than relying on the default behavior of Java's built-in exceptions.
By using custom exceptions, you can provide more meaningful error messages and handle specific error conditions in a more appropriate manner. You can create custom exceptions for any error condition that you want to handle in your code, making it easier to understand and debug your code.
Here's an example of a custom exception in Java
class InvalidAgeException extends Exception { public InvalidAgeException(String message) { super(message); } }
In this example, we have created a custom exception named InvalidAgeException that extends the Exception class. This custom exception will be used to handle the error condition when an invalid age is entered. To use this custom exception, you can throw it in your code when the error condition is met, like this:
void validateAge(int age) throws InvalidAgeException { if (age < 0) { throw new InvalidAgeException("Age cannot be negative."); } }
In this example, the validateAge method checks if the age entered is negative. If it is, then the InvalidAgeException is thrown with a meaningful error message. To catch this custom exception, you can use a try-catch block:
public static void main(String[] args) { try { validateAge(-10); } catch (InvalidAgeException e) { System.out.println(e.getMessage()); } }
In this example, the main method calls the validateAge method and catches the InvalidAgeException if it is thrown. The error message is then printed to the console.
Java Program to Throw Custom Exception
class InvalidAgeException extends Exception { public InvalidAgeException(String s) { super(s); } } public class CustomExceptionExample { static void validate(int age) throws InvalidAgeException { if (age < 18) { throw new InvalidAgeException("Not a valid age"); } else { System.out.println("Valid Age"); } } public static void main(String args[]) { try { validate(13); } catch (Exception m) { System.out.println("Exception Occurred: " + m); } } }Output
Exception Occurred: InvalidAgeException: Not a valid age