Posted on

Writing custom exception java

Javarevisited

Sometimes we need to create custom Exceptions in Java, i.e. Exceptions which are not defined in JDK or any third-party library your application is using. Though it’s widely recommended on several Exception best practices articles, even Joshua Bloch has recommended in Effective Java to prefer standard exception over custom exception, sometimes you really need it. There are certain guidelines to help to find whether you really need a custom exception or not.

  • Do you need an exception type that isn’t represented by those in the Java platform?
  • Would it help users if they could differentiate your exceptions from those thrown by classes written by other vendors?
  • Does your code throw more than one related exception?
  • If you use someone else’s exceptions, will users have access to those exceptions? A similar question is, should your package be independent and self-contained?

Custom Exception or Custom Message with Standard Exception?

For example if you declare an Exception that doesn’t provide any useful information other than a custom name then it probably uses generic Exception class with a custom message as shown in below example:

This custom exception doesn’t provide any extra information e.g. alternative ids, and that’s why can be easily replaced by a custom message and standard Exception class, as shown below:

Even better, if you think the client code is not going to take any action other than logging if the id is already taken, throw an unchecked exception:

Checked or Unchecked?

Once you make the decision to create a custom Exception, the next thing is to decide on checked vs unchecked exception. As I said before, by default make your exception unchecked and you will find whether it should be checked while writing client code. A general guideline is to make an exception unchecked if the client code is not going to take any action other than logging.

How to create Custom Exception in Java? Example

Here is our complete code example of creating custom or user defined Exception in Java. In our example, we have created NoSuchProductException , which is thrown by methods returning products. This is an unchecked Exception as we made it inherit from RuntimeException.

It inherit getMessage() method from Throwable and also has a method getProductId() which returns product id for which this exception has caused. Don’t make an Exception class as nested class even if it’s used only by one class, always declare Exceptions in their own class.

Things to remember while creating Custom Exception in Java

Though creating a custom, exception is as easy as subclassing java.lang.Exception class, there are few best practices you can follow to make most of it. There is so much criticism of checked exception due to boilerplate require to handle it, you will hardly create your custom exception as checked.

1) Don’t’ use Exception to control application behavior. Exception handling is very expensive as it requires native calls to copy stack trace, each time exception is created.

2) While creating a custom exception, prefer to create an unchecked, Runtime exception than a checked exception, especially if you know that client is not going to take any reactive action other than logging.

3) If your custom exception is created by passing another exception, then always contain original Exception as a source; use constructor which takes Exception rather than only message String.

4) Apart from providing default no argument constructor on your custom Exception class, consider providing at least two more constructors, one which should accept a failure message and other which can accept another Throwable as the cause.

5) If possible, avoid creating custom Exception and re-use existing, standard Exception classes from JDK itself. Most of the time you will realize that all you need is a form of IllegalArgumentException or ParseException or something similar.

6) While defining custom Exception, one of the most common mistake programmer make is to think that constructor is inherited from java.lang.Exception class, for example, they think that their Exception class will automatically inherit default no argument constructor and the one which takes a String message. T

his is not true. The constructor is not inherited in Java, not even default constructor. It’s actually added by the compiler rather than inherited from parent class. That’s why I have declared two constructors, one with String parameter and other as Throwable parameter:

This is actually the standard way of creating custom Exception in Java. In order to save time, you can even create a template of above class in Eclipse IDE.

7) For readable code, it’s good practice to append the string Exception to the names of all classes that inherits (directly or indirectly) from the Exception class e.g. instead of naming your class IncorrectPassword , name it IncorrectPasswordException .

That’s all about How to create custom Exception classes in Java. As I said, first try to avoid the temptation of creating a brand new Exception class, think if you can reuse existing ones. If you absolutely need, then make sure to follow best practices. At the bare minimum, make an effort to create unchecked exception rather than a checked one.

Java Program to Create custom exception

In this example, we will learn to create custom checked and unchecked exception in Java.

To understand this example, you should have the knowledge of the following Java programming topics:

Example 1: Java program to create custom checked exception

Output

In the above example, we have extended the Exception class to create a custom exception named CustomException . Here, we call the constructor of Exception class from the CustomException class using super() keyword.

Inside the method checkLanguage() , we have checked the exception condition, and if the exception occurs, the try..catch block handles the exception.

Here, this is the checked exception. We can also create unchecked exception class in Java. To learn more on checked and unchecked exception, visit Java Exception.

Example 2: Create custom unchecked exception class

Output

In the above example, we have extended the RuntimeException class to create an unchecked custom exception class.

Here, you can notice that, we haven’t declared any try. catch block. It is because the unchecked exception is checked at runtime.

Besides that, other functionality of unchecked exception is similar to the above mentioned program.