Throw clause Java Example Program

Syntax

if(<Condition>){
	throw new <ExceptionName>("Exception Statement");
}

Throw clause Example Program

public class ThrowClause {
    //Throw exception if number 1 is greater than 900
    static int add(int num1, int num2){
      if (num1 > 900){
         throw new ArithmeticException("Num 1 is greater than 900 and hence Exception is thrown");
      }else{
         System.out.println("Both parameters are correct!!");
      }
      return num1+num2;
   }
   public static void main(String args[]){
        Scanner scanner = new Scanner(System.in);
       System.out.println("Enter number 1 : ");
       int num1 = scanner.nextInt();
       System.out.println("Enter number 2 : ");
       int num2 = scanner.nextInt();
      int result=add(num1,num2);
      System.out.println("Result is : "+result);
   }
}

Sample Output 1

Enter number 1 : 
1000
Enter number 2 : 
700
Exception in thread "main" java.lang.ArithmeticException: Num 1 is greater than 900 and hence Exception is thrown
	at learnjavaprograms.ThrowClause.add(ThrowClause.java:18)
	at learnjavaprograms.ThrowClause.main(ThrowClause.java:30)
Java Result: 1

Sample Output 2

Enter number 1 : 
100
Enter number 2 : 
200
Both parameters are correct!!
Result is : 300