Youtube Channel

Creating user defined exception

In, java we can create our own exception on requirement by extending RunTimeException class , as shown below

***************************************************
package ExceptionHandling;

public class OverAgeException extends RuntimeException{
   
    public OverAgeException(String s) {
        super(s);

    }

}
****************************************************
package ExceptionHandling;

public class UnderAgeException extends RuntimeException{
    public UnderAgeException(String s) {

        super(s);
    }

}
****************************************************
package ExceptionHandling;

import java.util.Scanner;

public class AgeClientProgram {
    void setAge(int x)
    {
        if(x>60)
        {
            throw new OverAgeException("Sorry You are Senior citizen");
        }
        else if(x<18)
        {
            throw new UnderAgeException("Sorry you are teenager");
        }
        else
            System.out.println("Perfect mactch for this job");
    }

    public static void main(String[] args) {
        AgeClientProgram age=new AgeClientProgram();
        System.out.println("Enter age ");
        Scanner sc=new Scanner(System.in);
        int a=sc.nextInt();
        age.setAge(a);

    }

}
Next PostNewer Post Previous PostOlder Post Home