In Java, a custom exception is a user-defined class that extends the Exception class or one of its subclasses, such as RuntimeException. Custom exceptions help in providing more meaningful error messages specific to our application.
Basic Custom Exception
To create a custom exception, we just need to create a class that extends the Exception class.
|
1 2 3 4 5 6 7 |
// Custom Exception class class MyCustomException extends Exception { // Constructor public MyCustomException(String message) { super(message); // Call the parent class constructor } } |
Throwing the Custom Exception
To throw the custom exception, use the throw keyword within a method.
|
1 2 3 4 5 6 7 8 9 10 |
public class TestCustomException { public static void main(String[] args) { try { // Example condition to throw exception throw new MyCustomException("Something went wrong!"); } catch (MyCustomException e) { System.out.println("Caught exception: " + e.getMessage()); } } } |
Custom Exception with Multiple Constructors
We can add multiple constructors to our custom exception class. For example, one with a message and one with both a message and a cause.
|
1 2 3 4 5 6 7 8 9 10 11 |
class MyCustomException extends Exception { // Constructor with message public MyCustomException(String message) { super(message); } // Constructor with message and cause public MyCustomException(String message, Throwable cause) { super(message, cause); } } |
Runtime Custom Exception
If we want our exception to be unchecked (doesn’t require a try-catch block or throws declaration), we can extend RuntimeException instead of Exception.
|
1 2 3 4 5 |
class MyRuntimeCustomException extends RuntimeException { public MyRuntimeCustomException(String message) { super(message); } } |