User-defined Custom Exception in Java
Exceptions are runtime-errors that terminate a program abnormally. These are generally events that terminate the ongoing process. All Exceptions are child classes of the Throwable superclass.
Exceptions are of two types: IOException and Runtime Exception. Exceptions can also be divided into Checked and Unchecked Exceptions. Since this article comprises only User-Defined Exceptions, so the majority of the article will be based on User-Defined Exception only.
What is a User-Defined Exception?
user-defined exception is a custom, user-made exception created by the user in order to interrupt or terminate a process in his/her own program whenever a situation arises. A user-defined exception is creating our own Exception class and throwing that exception whenever required in the program.
Why do we need a User-Defined Exception?
Sometimes in your program, we need to terminate or interrupt a process in order to maintain the consistency of our program and also to ensure the smooth running of the module. These interrupts are not always a part of the default interrupts in the system. So thus we require to build our own exception classes. For example, in a banking system, if a person withdraws money from his/her account and the money withdrawal is more than the money present in the account. Then the transaction should immediately be stopped or terminated. Such a case is not present in the Java Libraries, and hence, they need to be manually coded. In such cases, we need a User-Defined Exception.
Steps to create a user-defined exception in Java
- Extend the
Exception
class. - Override
toString( )
method. Throw
the exception.
Down below, is a code to implement a user-defined exception.
public class Ex extends Exception{ public String toString(){ return "Insufficient Balance!"; } } class Ex1{ int with, bal; public void bank(int with, int bal){ try{ if(with>bal){ throw new Ex(); } bal = bal - with; System.out.println("New bal is "+bal); } catch(Ex e){ System.out.println(e); } } } class Test{ public static void main(String args[]){ int w=10000,b=1000; Ex1 ex = new Ex1(); ex.bank(w, b); } }
The code here simply returns “insufficient balance” if the withdrawn amount is greater than the account balance. In line#1 a class named Ex inherits Exception
class using extends
keyword. In line#2, toString( )
method is overridden to return “insufficient balance”. In class Ex1
, in line#12 the user-defined exception class is thrown if the withdrawn amount is greater than the balance.
OUTPUT:
insufficient balance
User-Defined Exceptions are one of the very important concepts of Java. This concept has been used in almost every bigger project done in Java.
Also, Read: An Object Oriented Approach of using Math.addExact( ) method in Java
Leave a Reply