In this article we will learn how to create user defined exceptions (own exceptions) and how to use them in Java programs.
Although Java provides several pre-defined exception classes, sometimes we might need to create our own exceptions which are also called as user-defined exceptions.
Steps for creating a user-defined exception:
- Create a class with your own class name (this acts the exception name)
- Extend the pre-defined class Exception
- Throw an object of the newly create exception
As an example for user-defined exception, I will create my own exception named NegativeException as follows:
class NegativeException extends Exception
{
String msg = "Value cannot be negative";
NegativeException() {}
NegativeException(String str)
{
msg = str;
}
public String toString()
{
return "NegativeException: " + msg;
}
}
Note that I am overriding the toString() method of the Exception class to provide meaningful description of my own exception.
Now, I can use my own exception NegativeException in Java programs as shown below:
class NegativeExceptionDemo
{
public static void main(String[] args)
{
try
{
int x = -5;
if(x < 0)
{
throw new NegativeException();
}
else
{
System.out.println("x = " + x);
}
}
catch(NegativeException e)
{
System.out.println(e);
}
}
}
Output of the above program is:
NegativeException: Value cannot be negative
From the above program you might have guessed the use of NegativeException. It notifies the user about negative values which are not allowed as input.
This how we can create and use our own exceptions in Java.
Suryateja Pericherla, at present is a Research Scholar (full-time Ph.D.) in the Dept. of Computer Science & Systems Engineering at Andhra University, Visakhapatnam. Previously worked as an Associate Professor in the Dept. of CSE at Vishnu Institute of Technology, India.
He has 11+ years of teaching experience and is an individual researcher whose research interests are Cloud Computing, Internet of Things, Computer Security, Network Security and Blockchain.
He is a member of professional societies like IEEE, ACM, CSI and ISCA. He published several research papers which are indexed by SCIE, WoS, Scopus, Springer and others.
Leave a Reply