ADVERTISEMENT
ADVERTISEMENT

Java program to demonstrate the throws keyword

Java example to demonstrate the throws keyword.
Submitted by Nidhi, on April 20, 2022

Problem Solution:

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.

Program/Source Code:

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 »


ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.