Pass Argument while throwing Exception Java Example Program


Syntax

throw new <exception_type> (<Argument thrown by exception>);

Pass Argument while throwing Exception Example Program

public class PassArgumentWhileThrowingException {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter number to be divided by 3 : ");
        int num1 = scanner.nextInt();
        int result = num1%3;
        if (result!=0){
            throw new ArithmeticException("The input number is not divisible by 3");
        }else{
            System.out.println("The input number is divisible by 3");
        }
    }
}

Sample Output 1

Enter number to be divided by 3 : 
18
The input number is divisible by 3

Sample Output 2 

Enter number to be divided by 3 : 
70
Exception in thread "main" java.lang.ArithmeticException: The input number is not divisible by 3
	at learnjavaprograms.PassArgumentWhileThrowingException.main(PassArgumentWhileThrowingException.java:19)
Java Result: 1