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
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
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.
How to create custom exceptions in Java
In the article Getting Started with Exception Handling in Java, you know how to catch throw and catch exceptions which are defined by JDK such as IllegalArgumentException , IOException , NumberFormatException , etc.
What if you want to throw your own exceptions? Imagine you’re writing a student management program and you want to throw StudentException , StudentNotFoundException , StudentStoreException and the like?
So it’s time to create new exceptions of your own.
We will call JDK’s exceptions built-in exceptions and call our own exceptions custom exceptions.
Let me tell you this: Writing custom exceptions in Java is very easy, but the important thing is, you should ask yourself this question:
1. Why do I need custom exceptions?
The answer could be very simple: When you couldn’t find any relevant exceptions in the JDK, it’s time to create new ones of your own.
By looking at the names of the exceptions to see if its meaning is appropriate or not. For example, the IllegalArgumentException is appropriate to throw when checking parameters of a method; the IOException is appropriate to throw when reading/writing files.
From my experience, most of the cases we need custom exceptions for representing business exceptions which are, at a level higher than technical exceptions defined by JDK. For example: InvalidAgeException , LowScoreException , TooManyStudentsException , etc.
2. Writing your own exception class
- Create a new class whose name should end with Exception like ClassNameException . This is a convention to differentiate an exception class from regular ones.
- Make the class extends one of the exceptions which are subtypes of the java.lang.Exception class. Generally, a custom exception class always extends directly from the Exception class.
- Create a constructor with a String parameter which is the detail message of the exception. In this constructor, simply call the super constructor and pass the message.
And the following example shows the way a custom exception is used is nothing different than built-in exception:
And the following test program handles that exception:
Run this program and you will see this output:
3. Re-throwing an exception which is wrapped in a custom exception
It’s a common practice for catching a built-in exception and re-throwing it via a custom exception. To do so, let add a new constructor to our custom exception class. This constructor takes two parameters: the detail message and the cause of the exception. This constructor is implemented in the Exception class as following:
public Exception(String message, Throwable cause)
Besides the detail message, this constructor takes a Throwable ’s subclass which is the origin (cause) of the current exception. For example, create the StudentStoreException class as following:
And the following example shows where the StudentStoreException gets thrown:
Here, suppose that the save() method stores the specified student information into a database using JDBC. The code can throw SQLException . We catch this exception and throw a new StudentStoreException which wraps the SQLException as its cause. And it’s obvious that the save() method declares to throw StudentStoreException instead of SQLException .
So what is the benefit of re-throwing exception like this?
Why not leave the original exception to be thrown?
Well, the main benefit of re-throwing exception by this manner is adding a higher abstraction layer for the exception handling, which results in more meaningful and readable API. Do you see StudentStoreException is more meaningful than SQLException , don’t you?
However, remember to include the original exception in order to preserve the cause so we won’t lose the trace when debugging the program when the exception occurred.
And the following code demonstrates handling the StudentStoreException above:
That’s about the lesson of writing custom exceptions in Java.
Other Java Exception Handling Tutorials:
About the Author:
Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.
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.