Custom Exception in Java

Custom Exception

Most of time Exception class handle all type of exception occur. But some cases we need a specific Exception and return a meaningful message to user.For this purpose we create our own exceptions by extending "Exception" class.
Below a simple user defined custom exception by extending Exception class.

 

package code.exception.mndclues;

public class CustomException extends Exception {
    public CustomException(String s) {
        super(s);
    }
}



First we create a custom class. My class name is CustomException which is extend Exception class

 

package code.example.basic;

public class CustomExceptionCall{
    public static void  main(String args[]){
        try{
            validateAge(15);
        }catch(Exception e){
            e.printStackTrace();
        }
    }
    static void validateAge(int age) throws CustomException{
        if(age>10){
            throw new CustomException("Age is not valid");
        }else{
            System.out.print("Age is valid");
        }
    }
}

output

code.example.basic.CustomException: Age is not valid
    at code.example.basic.CustomExceptionCall.validateAge(CustomExceptionCall.java:13)
    at code.example.basic.CustomExceptionCall.main(CustomExceptionCall.java:6)

Related Articles

post a comment