Java Custom Exceptions

In java we have already pre-defined exception classes to trigger on pre-defined conditions such as when you divide a number by zero it triggers ArithmeticException, when you perform some operation on ‘null’ it triggers NullPointerException, when we try to access invalid index on array it trigger ArrayIndexOutOfBoundsException … etc. But Java doesn’t trigger an exception when business rule is violated. Let’s discuss with an example.

Example 01 : To understand the need of custom exception

Output :

Before withdraw Balance : 1000
After withdraw Balance : -1000

In this example, At Line :17 we declared int accountBalance = 1000; Here int data type does allows even negative values also. That is the reason why at Line:22 even when we try to deduct more amount than available balance JVM didn’t throw exception. Because this is not JVM rule violation.

Here we should not allow JVM to execute Line:22, That means we should terminate withDrawAmount() method. To terminate we have to throw an exception. Here we can throw any predefined exception. So in the above example we can re-write withDrawAmount() method as follows.

In the above code snippet if withDrawalAmount > accountBalance then we are creating and throwing IllegalArgumentException. So that program will get terminated. Good thing here is we are not allowing the withdrawal when there are no sufficient funds in account.

But it is not recommended to use pre-defined exception for explaining ‘business failure’ scenario. It is always recommended to define custom exception for every business rule violation.

Here exactly we need the custom exception or user defined exception. We will rewrite above example with custom exception.

Example 02 : Create and throw user defined exception when business rule violated

Output :

Before withdraw Balance : 1000
Withdraw Failed : Insufficient Funds!!!
After withdraw Balance : 1000

In the above example, we defined user defined exception called ‘InsufficientFundsException’ to specify specific business rule violation. It is very clear and understandable exception.

Custom Exception

If we are creating exceptions as per our application need then we call them as ‘User defined exception’ or ‘Custom exception’. There are two types of custom exceptions.

  • Checked custom exception
  • Unchecked custom exception

Checked custom exception

Define a class by extending Exception class.

Unchecked custom exception

Define a class by extending Runtime class.

What is encapsulated in an Exception Object ?

The exception object contains namedescription and Call Stack of the exception. When we print the exception all these(name, description and call stack) together will be printed, All these together called exception stack trace.

What code we have to write in Custom Exception class

In Custom Exception class we define constructors (which intern invokes super class constructors) to pass custom exception message and root cause exception details to super class constructors.

As Custom Exception class is child of Exception or RuntimeException, So by default Custom Exception class inherits all the exception methods. In general we don’t override any methods in Custom Exception class.

Example 03 – Custom Exception – encapsulate description

Output :

main begin
Something went wrong
com.vidvaan.corejava.exception23.customexception.CustomExceptionDescriptionEncapsulation: Something wrong !!!
at com.vidvaan.corejava.exception23.customexception.Example03CustomExceptionEncapsulation.doStuff(
at com.vidvaan.corejava.exception23.customexception.Example03CustomExceptionEncapsulation.main(
main end

In the above example, in doStuff() method we are creating and throwing custom exception by encapsulating description into it. As we can see in the above output it print exception name, description and stack trace.

Example 04 – Custom Exception – encapsulate description and exception object

Output :

main begin
com.vidvaan.corejava.exception23.customexception.CustomException: Unable to read data from file !!!
at com.vidvaan.corejava.exception23.customexception.Example04CustomExceptionEncapsulation.readDataFromFile(
at com.vidvaan.corejava.exception23.customexception.Example04CustomExceptionEncapsulation.main(
Caused by: C:\demo.txt (The system cannot find the file specified)
at java.base/ Method)
at java.base/
at java.base/
at java.base/
at java.base/
at com.vidvaan.corejava.exception23.customexception.Example04CustomExceptionEncapsulation.readDataFromFile(
… 1 more
main end

In the above example, We are catching IOException and creating custom exception by encapsulating description and IOException object. The Great thing here is when exception is printed it will print custom exception stack trace and IOException stack trace too. So we are not loosing the root cause of the problem.

When ever we are creating custom exception, we should always encapsulate root cause exception into custom exception (if there is any root cause exception) so that we don’t loose root cause exception stack trace

In Custom exception class, if we want we can write our own variables and methods to pass some status along with the exception object as per business needs.

Scroll to Top