How to create custom exception in java with example

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:

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:

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.


About Manohar

I, Manohar am the founder and chief editor of ClarifyAll.com. I am working in an IT professional.

View all posts by Manohar →

Leave a Reply