User Defined Exception in Java

This tutorial will explain the User Defined Exception in Java. Java has good support for exception handling. Java also has a very good hierarchy in exception handling. Still, sometimes we need to create custom exceptions, i.e. Exceptions which are not defined in JDK or any third party library your application is using.

User-defined exceptions in Java are also known as Custom exceptions. Most of the times when we are developing an application in java, we often feel a need to create and throw our own exceptions. These exceptions are known as User defined or Custom exceptions. In this tutorial we will see, how can we create the Custom Exception class.

 

In Java, we can create the custom exception class. Let’s see the complete example of Custom exception, How can we create the exception class and how we can use it. We are taking the simplest example to understand the need of customized exception in Java.

 

Here we are creating a Java class BankAccount, which is representing a bank account where we can deposit and withdraw money. But what will happen if we want to withdraw money which exceeds your bank balance? We will not be allowed to do this, and this is where user defined exception comes into the picture.

So here we need to create the custom exception class. We are creating a custom exception class named NotSufficentBalanceException .

Let’s see the sample code of these class. First, see the exception class code-

 

Now let’s implement the BankAccount class. In this class, we are declaring the current Bank Account and withdraw method implementation and deposit method implementation. Let’s see the code of BankAccount class-

 

We have seen the code of both the class. Now create the new class which will implement the code in with we withdraw amount and it will throw the custom exception while we will try to withdraw the invalid amount.

Now let’s run the ‘WithDrawAmount‘ class and observe the output. Output will be —

Current balance : 2000
Withdrawing 200
Current balance : 1800
Exception in thread “main” NotSufficentbalanceException: Current balance 1800 is less than requested amount 2000
at BankAccount.withdraw(BankAccount.java:15)
at WithDrawAmount.main(WithDrawAmount.java:11)

Now, that’s all how can we create a user-defined exception in Java and use it.

 

Selenium Tutorial:

If you liked this video, then please subscribe to our YouTube Channel for more video tutorials.

0 Comment

Leave a Reply