欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

throws_Keyword

程序员文章站 2022-07-14 10:41:37
...

Java throws Keyword

Java Exceptions Tutorial
The Java throws keyword is used to declare an exception. It gives an information to the programmer that there may occur an exception so it is better for the programmer to provide the exception handling code so that normal flow can be maintained.
Exception Handling is mainly used to handle the checked exceptions. If there occurs any unchecked exception such as NullPointerException, it is programmers fault that he is not performing checkup before the code is used.
The syntax of Java throws Keyword
return_type method_name() throws exception_class_name{
//method code
}
We declare only checked exception using a throws keyword. Let’s see an example to demonstrate the usage of a throws keyword.
Basically, whenever exception arises there two cases, either you should handle the exception using try/catch or you declare the exception i.e. specifying throws with the method.

throws Keyword Example

In this example, the exceptionWithoutHandler(), exceptionWithoutHandler1() and exceptionWithoutHandler2() methods uses throws keyword to declare exception.

public class ExceptionHandlingWorks {
    public static void main(String[] args) {
         exceptionHandler();
    }

 private static void exceptionWithoutHandler() throws IOException {
     try (BufferedReader reader = new BufferedReader(new FileReader(new File("/invalid/file/location")))) {
          int c;
          // Read and display the file.
          while ((c = reader.read()) != -1) {
               System.out.println((char) c);
          }
     }
 }

 private static void exceptionWithoutHandler1() throws IOException {
      exceptionWithoutHandler();
 }

 private static void exceptionWithoutHandler2() throws IOException {
      exceptionWithoutHandler1();
 }

 private static void exceptionHandler() {
     try {
          exceptionWithoutHandler2();
      } catch (IOException e) {
          System.out.println("IOException caught!");
      }
   }
}
相关标签: throws关键字

推荐阅读