Home »
Java programming language
Creating User Defined Exceptions in Java
Learn: What is User Defined Exception in Java? How to create a custom or user defined Exception?
Submitted by Abhishek Jain, on September 05, 2017
So far you would have been known, how to be handled the exceptions in java thatare thrown by the Java API but sometimes you may occasionally need to throw your ownexception i.e. if you encounter a situation where none of those exception describe yourexception accurately or if you can't find the appropriate exception in the Java API, you can codea class that defines an exception that is more appropriate and that mechanism of handling exception is called Custom or User Defined Exception.
In Java API all exception classes have two type of constructor. First is called default constructorthat doesn't accept any arguments. Another constructor accepts a string argument thatprovides the additional information about the exception. So in that way the Custom exceptionbehaves like the rest of the exception classes in Java API.
There are two primary use cases for a custom exception:
- your code can simply throw the custom exception when something goes wrong.
- You can wrap an exception that provides extra information by adding your ownmessage.
The code of a Custom exception:
public class ExceptionClassNameextends Exception
{
publicExceptionClassName(){ }
publicExceptionClassName(StringMessage)
{
super(message);
}
}
Consider the program:
import java.util.*;
class StudentManagement extends Exception
{
StudentManagement(String errmsg)
{
super(errmsg);
}
}
class UserDefinedException
{
public static void main(String arg[])
{
try
{
Scanner KB=new Scanner(System.in);
System.out.print("Enter Percentage:");
int per=KB.nextInt();
if(!(per>=0 && per<=100))
{
throw(new StudentManagement("Invalid Percentage...."+per));
}
else
{
System.out.println("Valid Percentage...");
}
}
catch(StudentManagement e)
{
System.out.println(e);
}
}
}