To create a custom exception in Java, you need to define a new class that extends one of the existing exception classes or their subclasses. Here’s an example of how to create a custom exception:
1 2 3 4 5 |
public class CustomException extends Exception { public CustomException(String message) { super(message); } } |
In the example above, CustomException
is a custom exception class that extends the Exception
class. It provides a constructor that accepts a String
parameter for the exception message, which is passed to the super
constructor of the Exception
class.
You can now use your custom exception in your code, throw it, and handle it as needed. Here’s an example of how you can use the custom exception:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
public class Example { public static void main(String[] args) { try { performOperation(); } catch (CustomException e) { System.out.println("Custom exception caught: " + e.getMessage()); } } public static void performOperation() throws CustomException { // Perform some operation that may throw the custom exception boolean operationFailed = true; if (operationFailed) { throw new CustomException("Custom exception occurred"); } } } |
In the Example
class, the performOperation()
method is declared to throw CustomException
. Inside the method, you can throw the custom exception using the throw
keyword, passing an instance of CustomException
with an appropriate error message.
In the main
method, the performOperation()
method is called inside a try-catch block. If the performOperation()
method throws a CustomException
, it is caught in the catch block, and the error message is printed.
By creating custom exceptions, you can define and handle specific exceptional scenarios in your application, providing more meaningful error messages and allowing for better error handling and recovery.