Sometimes, you want to create your own error messages to explain problems clearly in your program. Custom exceptions help you do that.
0
0
Throwing custom exceptions in Java
Introduction
When you want to show a specific error that built-in exceptions don't cover.
When you want to make your program easier to understand by naming errors clearly.
When you want to handle special cases differently in your program.
When you want to pass extra information about an error.
When you want to separate your error handling from general errors.
Syntax
Java
public class MyException extends Exception { public MyException(String message) { super(message); } } // To throw the exception: throw new MyException("Error message here");
You create a new class that extends Exception or RuntimeException.
Use throw keyword to throw your custom exception.
Examples
This example creates an
AgeException to check if age is less than 18.Java
public class AgeException extends Exception { public AgeException(String message) { super(message); } } // Throwing it if (age < 18) { throw new AgeException("Age must be 18 or older"); }
This example uses
RuntimeException so you don't have to declare it in method signature.Java
public class NegativeNumberException extends RuntimeException { public NegativeNumberException(String message) { super(message); } } // Throwing it if (number < 0) { throw new NegativeNumberException("Number cannot be negative"); }
Sample Program
This program defines a custom exception AgeException. It checks if age is less than 18 and throws the exception if so. The main method tries two ages and catches the exception to print the message.
Java
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 18 or older"); } 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()); } try { checkAge(20); } catch (AgeException e) { System.out.println("Caught exception: " + e.getMessage()); } } }
OutputSuccess
Important Notes
Custom exceptions make your code clearer and easier to debug.
Checked exceptions (extend Exception) must be declared or caught.
Unchecked exceptions (extend RuntimeException) do not need to be declared or caught.
Summary
Custom exceptions let you create your own error types with clear messages.
Use throw new YourException() to signal an error.
Catch your custom exceptions to handle errors gracefully.