User Defined or Custom Exceptions

We are now aware of the basic Exception Handling in Java, but there are User Defined Exceptions we need to discuss about, that we use very often to customize this exception handling. There can be several scenarios based on which we can decide using the User Defined Exceptions such as:

  1. Specifying our own custom exception messages to be logged, instead of the default JVM exception messages.
  2. Defining our own exception scenarios and throwing our own custom exceptions with our own custom messages, which might include scenarios like:
    • a) Calling any unimplemented abstract class method.
    • b) Using any unacceptable special characters, as part of server side validations.

So now, the question is, how can we create such User Defined Exceptions or Custom Exceptions?

  1. Create a new java class and name it to anything readable like MyException.java
  2. Extend the class with Exception class, add a private errorMessage property and create a parametrized constructor inside, as shown below:

Let’s have a little explanation to what has been done above. We have create a parametrized constructor that takes a “String” argument, which is passed to the super class constructor(super class here is the Exception class) as super(errorMessage).  Now java creates a new Exception with the message as in the string errorMessage that has been passed.


Now that we have the MyException class created, let’s see how can we use it.

Create a new class ExceptionDemo.java with the main method as below:

As the output of this implementation, we could see the custom exception getting logged as:

in thread “main” com.jcombat.examples.MyException: My Exception Occurred
at com.jcombat.examples.ExceptionDemo.someMethod(ExceptionDemo.java:18)
at com.jcombat.examples.ExceptionDemo.main(ExceptionDemo.java:8)

Note that:

The custom exceptions acts as a wrapper to the actual exceptions that get generated. Therefore the wrapping must be done with utter care. It is always better to provide the original exception object to the new custom exception’s constructor that is thrown. You can try that out creating another constructor inside the MyException class, with the Exception object as one of it’s parameters.

Receive our updates to your inbox

Get more stuff like this
in your inbox

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.