Throws clause Java Example Program


Syntax

<return_type> <method_name>() throws <exception_name>{
	//Do Something
}


Throws clause Example Program

public class ThrowsClause {
    //Throws exception if any number is divided by 0
    static int divide(int num1, int num2) throws ArithmeticException{
        int result = num1/num2;
    return result;
    }
   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=divide(num1,num2);
        System.out.println("Result is : "+result);
   }
}


Sample Output 1

Enter number 1 : 
100
Enter number 2 : 
0
Exception in thread "main" java.lang.ArithmeticException: / by zero
	at learnjavaprograms.ThrowsClause.divide(ThrowsClause.java:17)
	at learnjavaprograms.ThrowsClause.main(ThrowsClause.java:26)
Java Result: 1


Sample Output 2 

Enter number 1 : 
20
Enter number 2 : 
7
Result is : 2