Custom Exception Java Example program


Syntax

class <exception_name> extends Exception{  
    <exception_name>(String s){  
    super(s);  
    }  
}

Program

public class CustomException {
    static void validateInput(int number) throws InvalidInputException{
        if(number>100){
            throw new InvalidInputException("Exception");
        }else{
            System.out.println("The provided input is valid");
        }
    }
    
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter a number less than 100 :  ");
        int number = scanner.nextInt();
        try{
            validateInput(number);
        }catch(InvalidInputException e){
            System.out.println("Caught Exception - Input is greater than 100");
        }
    }
}

class InvalidInputException extends Exception{  
    InvalidInputException(String exceptionText){  
        super(exceptionText);  
    }    
}

Sample Output 1

Enter a number less than 100 :  
19
The provided input is valid

Sample Output 2 

Enter a number less than 100 :  
1000
Caught Exception - Input is greater than 100