Java 中的 Try、catch、throw 和 throws

javaobject oriented programmingprogramming更新于 2025/12/22 9:16:17

Java 中的 Try 和 catch

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

以下是 try 和 catch − 的语法

try {
   // 受保护的代码
} catch (ExceptionName e1) {
   // Catch 块
}

catch 语句涉及声明您尝试捕获的异常类型。如果在受保护的代码中发生异常,则会检查 try 后面的 catch 块(或多个块)。如果发生的异常类型在 catch 块中列出,则异常将传递给 catch 块,就像将参数传递给方法参数一样。

示例

现在让我们看一个实现 try 和 catch − 的示例

import java.io.*;
public class Demo {
   public static void main(String args[]) {
      try {
         int a[] = new int[5];
         System.out.println("Access element eighth :" + a[7]);
      } catch (ArrayIndexOutOfBoundsException e) {
         System.out.println("Exception thrown :" + e);
      }
      System.out.println("Out of the block");
   }
}

输出

Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 7
Out of the block

Java 中的 throw 和 throws

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

您可以使用 throw 关键字抛出异常,无论是新实例化的异常还是刚刚捕获的异常。

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


相关文章


有用资源