Custom Exception in java

Java provides us facility to create our own exceptions which are basically derived classes of Exception. For example MyException extends the Exception class.

We pass the string to the constructor of the super class- Exception which is obtained using getMessage() method on the object created.


Let's see a simple example of Java custom exception.

// A Class that represents use-defined expception
class MyException extends Exception
{
    public MyException(String s)
    {
        // Call constructor of parent Exception
        super(s);
    }
}
 

A Class that uses above MyException

// A Class that uses above MyException
public class Main
{
    // Driver Program
    public static void main(String args[])
    {
        try
        {
            // Throw an object of user defined exception
            throw new MyException("Durgesh");
        }
        catch (MyException ex)
        {
            System.out.println("Caught");
 
            // Print the message from MyException object
            System.out.println(ex.getMessage());
        }
    }
}
Caught
Durgesh

Example of creating and using Custom Exception.

//program to create InvalidAgeException and using it
import java.util.Scanner;
class InvalidAgeException extends Exception
{
    InvalidAgeException(String msg)
    {
        super(msg);
    }
}

/*now create another class which contain
 main mehtod and use this exception
*/
class Executor
{
 public static void main(String[] args) {
  try
    {
    //use scanner to take input from user
     Scanner ob=new Scanner(System.in);
     System.out.println("Enter your age");
     int age=ob.nextInt();
     if(age<18)
     {
     throw new InvalidAgeException("Your age is invalid !!");
     }
     System.out.println("Hello your age is "+age);
     System.out.println("Successfully voted..");
    }catch(Exception e)
    {
     System.out.println(e.getMessage());
    }
  }
 }
Enter your age
14
Your age is invalid !!