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 用于显式地引发异常。
广告
数据结构
网络
关系型数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP