Home »
Java »
Java Programs
Java program to demonstrate the throws keyword
Java example to demonstrate the throws keyword.
Submitted by Nidhi, on April 20, 2022
Problem statement
In this program, we will create a method with the "throws" keyword. The throws keyword is used to declare an exception with a method. It informs the programmer that there may occur an exception.
Java program to demonstrate the throws keyword
The source code to demonstrate the throws keyword is given below. The given program is compiled and executed successfully.
// Java program to demonstrate throws keyword
public class Main {
public static void division(int num1, int num2) throws ArithmeticException {
//code that may generate ArithmeticException
int res = 0;
res = num1 / num2;
System.out.println("Division is: " + res);
}
public static void main(String[] args) {
try {
division(10, 0);
} catch (Exception e) {
System.out.println("Exception: " + e);
} finally {
System.out.println("The finally block executed");
}
System.out.println("Program Finished");
}
}
Output
Exception: java.lang.ArithmeticException: / by zero
The finally block executed
Program Finished
Explanation
In the above program, we created a class Main. The Main class contains division and main() methods. In the division() method, we declared ArithmeticException using the "throws" keyword. It describes, that the division() method may generate an Arithmetic exception.
The main() method is the entry point for the program. And, created try, catch, and finally blocks. In the try block, we called the division() method and handled the exception in the catch block.
Java Exception Handling Programs »