Java Program to Create custom exception

Java Program to Create custom exception

What are Exceptions?

In Java, an exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions. Exceptions are typically caused by errors, such as a divide-by-zero error or an attempt to access an array element that is out of bounds. When an exception occurs, the Java runtime system creates an exception object and throws it.

In this Article, we will write a program to Create custom exception.

Exceptions in Java :

Java has a built-in exception hierarchy, with Throwable as the base class for all exceptions. Throwable has two direct subclasses.

  1. Exception is the base class for all exceptions that indicate a problem with the application code and are intended to be handled by the developer.
  2. Error is the base class for all exceptions that indicate a problem with the runtime environment and are not intended to be handled by the developer.
There are several types of standards in Java, such as :
  • IOException : for input/output operations related issues
  • SQLException : for database related issues
  • IllegalArgumentException : when a method is passed an illegal or inappropriate argument
  • NullPointerException : when an application attempts to use null in a case where an object is required
  • ArrayIndexOutOfBoundsException: when an application attempts to access an index of an array that is out of bounds.

Program to Create custom exception :

Run
// Exception class
class InvalidAgeException extends Exception {
    public InvalidAgeException(String message) {
        
        // function calling for exception
        super(message);
    }
}

class Main{
    
    // Function for age validation 
    static void validateAge(int age) throws InvalidAgeException {
        
        // Condition for validating the exception 
        if (age < 18)
            throw new InvalidAgeException("Not a valid age");
        else
            System.out.println("Welcome to vote");
    }

    public static void main(String args[]) {
        
        // try block to call validate age function
        try {
            validateAge(13);
        } 
        // Exception block
        catch (InvalidAgeException m) {
            System.out.println("Exception occured: " + m);
        }
    }
}

Explanation:

In this example, we have created a custom InvalidAgeException by extending the base class. We have overridden the constructor of the base class to accept a string message.
We have a static method validateAge which takes age as an argument and throws InvalidAgeException if age is less than 18.
In the main method, we call the validateAge method and catch the InvalidAgeException if it is thrown.

It is important to note that when creating custom exceptions, it is a good practice to provide a constructor that accepts a meaningful error message or reason as an argument, so that it can be easily understood what caused the exception.

Program to Create custom unchecked exception class :

Run
// create a unchecked exception class
class MyUncheckedException extends RuntimeException {
    public MyUncheckedException(String message) {
        
        // calling the constructor of RuntimeException
        super(message);
    }
}

public class Main {
    public static void main(String[] args) {
        
        // Exception try block
        try {
            throw new MyUncheckedException("This is my custom unchecked exception");
        } 
        // catch block of Exception
        catch (MyUncheckedException e) {
            e.printStackTrace();
        }
    }
}

Explanation:

In this example, We have created a custom unchecked exception class called “MyUncheckedException” which extends the built-in “RuntimeException” class. In the main method, We are throwing an instance of “MyUncheckedException” with a custom message and catching it to print the stack trace.

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription