尝试,捕捉,抛出和抛出Java

尝试赶上Java

一种方法使用try和catch关键字的组合来捕获异常。在可能产生异常的代码周围放置了一个try / catch块。

以下是try and catch的语法-

try {
   //受保护的代码
} catch (ExceptionName e1) {
   //渔获
}

catch语句涉及声明您要捕获的异常类型。如果受保护的代码中发生异常,则将检查try之后的catch块。如果在catch块中列出了发生的异常类型,则将异常传递到catch块的方式与将参数传递给方法参数的方式一样。

示例

现在让我们看一个实现try and catch的示例-

import java.io.*;
public class Demo {
   public static void main(String args[]) {
      try {
         int a[] = new int[5];
         System.out.println("第八个访问元素:" + a[7]);
      } catch (ArrayIndexOutOfBoundsException e) {
         System.out.println("抛出异常:" + e);
      }
      System.out.println("Out of the block");
   }
}

输出结果

抛出异常:java.lang.ArrayIndexOutOfBoundsException: 7
Out of the block

抛出Java

如果方法不处理检查的异常,则该方法必须使用throws关键字对其进行声明。throws关键字出现在方法签名的末尾。

您可以使用throw关键字引发异常,可以是新实例化的异常,也可以是刚刚捕获的异常。

throws用于推迟对已检查异常的处理,throw用于显式调用异常。