Categories: Java

Java custom( user-defined) exception

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

Share
Published by
Rabecca Fatima

Recent Posts

Find Intersection of Two Singly Linked Lists

You are given two singly linked lists that intersect at some node. Your task is…

4 months ago

Minimum Cost to Paint Houses with K Colors

A builder plans to construct N houses in a row, where each house can be…

4 months ago

Longest Absolute Path in File System Representation

Find the length of the longest absolute path to a file within the abstracted file…

4 months ago

Efficient Order Log Storage

You manage an e-commerce website and need to keep track of the last N order…

5 months ago

Select a Random Element from a Stream

You are given a stream of elements that is too large to fit into memory.…

5 months ago

Estimate π Using Monte Carlo Method

The formula for the area of a circle is given by πr². Use the Monte…

5 months ago