Java 中的 try、catch、throw 和 throws


Java 中的 try 和 catch

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

以下是 try 和 catch 的语法:

try {
   // Protected code
} catch (ExceptionName e1) {
   // Catch block
}

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 用于显式地引发异常。

更新于: 2019年9月26日

2K+ 次查看

启动您的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.