Because our own exceptions are derived classes of Exception, Java allows us to create them. A custom exception or user-defined exception is one we create on our own. Java custom exceptions are used to tailor the exception to user requirements. A User-Defined Exception, also known as a custom exception, is your own exception class that you create and then throw using the keyword “throw.”
Need for custom exception :
- To detect a subset of current Java exceptions and give them a particular treatment.
- Exceptions to business logic These are the business logic and workflow exceptions. Understanding the precise issue is helpful for both application users and developers.
Example:
Let’s see a simple example of a Java custom exception. In the following code, the constructor of InvalidAgeException takes a string as an argument. This string is passed to the constructor of the parent class Exception using the super() method. Also, the constructor of the Exception class can be called without using a parameter, and calling super() method is not mandatory.
// class representing custom exception
class InvalidAgeException extends Exception
{
public InvalidAgeException (String str)
{
// calling the constructor of parent Exception
super(str);
}
}
// class that uses custom exception InvalidAgeException
public class TestCustomException1
{
// method to check the age
static void validate (int age) throws InvalidAgeException{
if(age < 18){
// throw an object of user defined exception
throw new InvalidAgeException("age is not valid to vote"); }
else {
System.out.println("welcome to vote");
}
}
// main method
public static void main(String args[])
{
try
{
// calling the method
validate(13);
}
catch (InvalidAgeException ex)
{
System.out.println(" Caught the exception");
// printing the message from InvalidAgeException object
System.out.println("Exception occured: " + ex);
}
System.out.println("rest of the code...");
}
}
Output:
Caught the exception
Exception occured: age is not valid to vote
rest of the code...
Note: also read about the Interface vs Abstract class
Follow Me
If you like my post, please follow me to read my latest post on programming and technology.
https://www.instagram.com/coderz.py/
https://www.facebook.com/coderz.py
Staying up to the mark is what defines me. Hi all! I’m Rabecca Fatima a keen learner, great enthusiast, ready to take new challenges as stepping stones towards flying colors.
Leave a Comment