Programming Examples

Are you a Programmer or Application Developer or a DBA? Take a cup of coffee, sit back and spend few minutes here :)

Custom Exception in Java – Creating & Using

1. Custom Exceptions

In Java there are many Exception types to handle a unique exception. There are groups like security related exceptions, file handling related exception and DB operation related exceptions, etc. If you want to handle an exception that is more exact to your business Logic, you can go for ‘Custom Exception’. Before we move on to the topic, let us learn Exception Category and this will help us decide what kind of exception we can create.

You can read Exception Handling before reading this topic. It is also advised to have knowledge on how to handle multiple exception with one try catch block.

2. Exception Types

Have a look at the below picture:

Checked And Unchecked Exceptions

You may have heard a program throws an exception or error when doing a specific operation. So, there is some piece of code which throws an Exception or Error. We can recover from the Exception, but the same we cannot do with an error. The class Throwable has the base to throw the exception or Error. The Error class is the one which Java SDK uses to report error situation to JVM. All the error reporting classes provide functionality of throwing it from the code where the error or exception condition crops up. Java has two types of exceptions. They are Checked Exceptions and Unchecked Exceptions.

2.1 Program Error – Fatal

There are conditions which cannot be recovered. For example, a program running into out-of-memory. We cannot recover from this error by providing a handling code. Java throws an error here instead of Exception. People often call this as Fatal Error. Means, the program can not catch this and take safe route. These fatal error ends the program abnormally. Java SDK uses the Error class to report the fatality situation to the JVM. On seeing these fatal error JVM halts the program.

2.2 Checked and Unchecked Exceptions

Unchecked Exceptions are left to the user choice. They can either handle the exception and they can leave it. For example, the NullPointerException has the possibility raised everywhere in the code. So, it is up to the user to decide if the code should handle it. The coder knows the possibility of getting null reference when they write it and decides.

Java forces to handle the Checked Exceptions. If we do not handle it, Java compiler won’t make byte code. The examples for Checked Exception are: SQLException, FileNotFoundException. In this example, we will set up our own exception, which falls under Checked Exception.

2.3 Exception Class

The Exception Class is the base for all the Exceptions in Java. The Exception class falls under Checked Exception Category. Since it is the base for all the Exceptions, it can handle any exception type. In this example, we will derive a class from this Exception class. So, our custom exception falls under checked exception category. Means, Java forces the code to handle the exception when they use the function which is rising it.

2.4 RuntimeException Class

The RuntimeException class falls under Unchecked Exception category. So, when we derive a class from it, java will not perform a check for handling this exception. Therefore, when user want to handle it, they can do so or else they can leave it.

You can watch the exception Categories as a video below:

Video 1: Exception Types

3. The Product Class – To Demo Custom Exception

In this section, we will create a Product class. We use this class to learn how the client handles our custom exception.

3.1 Product Class with Three Data Member

The product class has three members. Upon three, Two of the members hold product id and product name. The third member will store quantity on hand. This member involves in our custom exception. Below is the code:


3.2 Constructor of Product Class

In the constructor, we will load all the product members. Here, we set the StockInHand member to zero. The function members will add or remove quantities from the member.


3.3 Representing Product class String

The Product class overrides the toString member to represent it as a string. This will be useful to output the product in string format. Below is the toString override:


3.4 Stock Management Needs Custom Exception!

Product class provides three member functions to manage the stock in hand data member. The method purchase will add quantities to the stock while sell method negates it. The sell method calls an internal private method takeStock. This method alters the data member StockInHand to negate the number of sales made. These methods are below:


3.5 Using the Product Class From Main

The main method first creates the Product class instance. In the below code, we create a product Pen with an ID 101. Recall, the constructor will initialize the stock of Pen as 0.

After creating the object, we purchase 10 quantity of pen by making call to the purchase method. Now, pen instance contains 10 number of pens.

Then we sell 7 quantity of pen using the sell method and pushing the quantity to 3. Now comes the need for custom exception. The client code here performs a sale of 5 pen second time. But, the quantity in hand is 3 and our product class should have a way to inform this to the client code. The client code here in our case is the main method. But, in the real world, it may be any UI application (Web or Desktop). This is how we land-up creating our own Exception as we do not find any build-in Exception type to show ‘out-of-stock’.

4. Custom Exception – OutOfStockException

In the past section, we saw user can make a mistake of calling the sell with a quantity exceeding the stock in hand. We should not allow such a call. When we tie the custom checked exception with the sell method, the Java compiler will force the user to wrap the call to sell with a try-catch block. Now we will create OutOfStockException which is a custom exception. We just need to create the class which extends from the built-in Exception class. Note, it is good practice to provide support for all the versions of constructor and we no need to implement it at all. Just delegating the call to base class constructor using super keyword do the job. Below is the code:

Now we are ready with the custom exception class that satisfy the need of sell method in the product class. Let us see how the product class uses it.

5. Throw versus Throw in Java

5.1 Product Class Throwing the Custom Exception

Now, we will change the product class to make use of the Custom Exception. First, we change the takeStock method to show that it throws an Exception of type OutOfStockException. Here we use the throws keyword. Next, we check the claimed quantity against the quantity in hand. As you guessed, when the claimed quantity is not right, we raise the OutOfStockException using the throw keyword. See how we create an instance of the Exception object and give it to the throw keyword.

Note, the throws keyword is used to mark a method, and it tells the java compiler that the method throws an exception. The throw keyword constructs the exception object and throws. Below is the code:

5.2 Product Class Catching the Custom Exception

The user of the takeStock is one more member function in the same class. It is the sell method with public scope. Here, we handled the exception in the sell method itself. The caller can know that there was an exception by looking at the console window. The code is below:

Note, if you want the client of the product class to handle the exception, you can delegate the exception which you can see in the below video.

Video 2: Custom Exception

6. Code Reference – Custom Exception Example

Listing 1:

Listing 6.2

Listing 6.3

Categories: Java

Tags: , , ,

Do you like this Example? Please comment about it for others!!

This site uses Akismet to reduce spam. Learn how your comment data is processed.