How to write your own custom Exception class in Java

Rohit Singh
2 min readOct 14, 2017

I assume that you already know the What and Why part of the exception handling in general.

While developing something, you would have crossed path with FileNotFoundException or NullPointerException.

But what if you want to create your own custom exception messages when something goes wrong in your application. For example, you are writing one shopping application and you have to throw an exception if the account balance is less than that you are going to purchase

Sorry, insufficient balance!

How to do that?

Simple! You got to remember only one keyword. throw

In Java, throw keyword is used to create an Exception object and pass to JVM(eventually, there is a reason I said eventually. may be in next post)

Let's create InsufficientBalanceException

  1. Write a class which extends RuntimeException
class NotSufficientBalanceException extends RuntimeException{

public NotSufficientBalanceException(String errorMessage)
{
super(errorMessage);
}

}

2. Throw Exception

public void buy(int x)
{
if(balance<x) throw new NotSufficientBalanceException("Not Enough Balance"); else
{
balance = balance - x;
}
}

That’s pretty much of it.

BONUS

You can see a use case example with the full code here in my Data Structure Git Repository.
How to throw Stackoverflow/ Underflow, QueueOverflow/UnderFlow Exception.

Putting up content takes a lot of time and effort 😓.
👏 clap 👏 If you think you learned something from this article.
You can find me on Stackoverflow,Github,and,on Linkedin.
Give feedback and feel free to correct mistakes.

--

--

Rohit Singh
Rohit Singh

Written by Rohit Singh

Android Developer | Arizona State University | NASA Psyche Research Aide

No responses yet