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:

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.
1 2 3 |
public static void main(String[] args) { //Sample 02: Create Product Class Product pen = new Product(101, "Pen"); |
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.
1 2 3 |
//Sample 03: Purchase the Product pen.purchase(10); System.out.println(pen); |
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’.
1 2 3 4 5 6 |
//Sample 04: Sell the Product pen.sell(7); System.out.println(pen); pen.sell(5); System.out.println(pen); } |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
package com.Prod; //Sample 05: Custom Exception public class OutOfStockException extends Exception { public OutOfStockException() { } public OutOfStockException(String message) { super(message); } public OutOfStockException(Throwable cause) { super(cause); } public OutOfStockException(String message, Throwable cause) { super(message, cause); } public OutOfStockException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } } |
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:
1 2 3 4 5 6 7 8 9 |
//Sample 05: State the method throws OutOfStockException private void takeStock(int Qty) throws OutOfStockException { //Sample 5.1: Throw OutOfStockException when //Quantity exceeds stock if (Qty > StockInHand) throw new OutOfStockException("Stock Insufficient!!" ); StockInHand = StockInHand - Qty; } |
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:
1 2 3 4 5 6 7 8 9 |
public void sell(int Qty) { //Sample 6.0: Handle out of Stock Situation try { takeStock(Qty); } catch (OutOfStockException e) { System.out.println(e.getMessage()); } } |
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: OutOfStockException.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
package com.Prod; //Sample 05: Custom Exception public class OutOfStockException extends Exception { public OutOfStockException() { // TODO Auto-generated constructor stub } public OutOfStockException(String message) { super(message); // TODO Auto-generated constructor stub } public OutOfStockException(Throwable cause) { super(cause); // TODO Auto-generated constructor stub } public OutOfStockException(String message, Throwable cause) { super(message, cause); // TODO Auto-generated constructor stub } public OutOfStockException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); // TODO Auto-generated constructor stub } } |
Listing 6.2 Product.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
//Sample 01: The Product Class package com.Prod; public class Product { private int ProdId; private String ProdName; private int StockInHand; //1.1: Ctor Product(int id, String name) { ProdId = id; ProdName = name; StockInHand = 0; } //1.2: toString Override @Override public String toString() { return ProdId + ":" + ProdName + "[" + + StockInHand+ "]"; } //1.3: Sales and Purchase of Quantity public void purchase(int Qty) { StockInHand = StockInHand + Qty; } //Sample 05: State the method throws OutOfStockException private void takeStock(int Qty) throws OutOfStockException { //Sample 5.1: Throw OutOfStockException when //Quantity exceeds stock if (Qty > StockInHand) throw new OutOfStockException("Stock Insufficient!!" ); StockInHand = StockInHand - Qty; } public void sell(int Qty) { //Sample 6.0: Handle out of Stock Situation try { takeStock(Qty); } catch (OutOfStockException e) { System.out.println(e.getMessage()); } } } |
Listing 6.3 MainEntry.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
package com.Prod; public class MainEntry { public static void main(String[] args) { //Sample 02: Create Product Class Product pen = new Product(101, "Pen"); //Sample 03: Purchase the Product pen.purchase(10); System.out.println(pen); //Sample 04: Sell the Product pen.sell(7); System.out.println(pen); pen.sell(5); System.out.println(pen); } } |
Categories: Java
Tags: Checked Exception, Custom Exception, throw keyword, throws keyword