Java 中的 try...catch
块用于处理异常,并防止程序异常终止。
这是 Java 中 try...catch
块的语法。
try{
// code
}
catch(exception) {
// code
}
try
块包含可能生成 异常 的代码。
catch
块包含在 try
块中发生异常时要执行的代码。
示例:Java try...catch 块
class Main {
public static void main(String[] args) {
try {
int divideByZero = 5 / 0;
System.out.println("Rest of code in try block");
}
catch (ArithmeticException e) {
System.out.println("ArithmeticException => " + e.getMessage());
}
}
}
输出
ArithmeticException => / by zero
在上面的示例中,请注意这一行:
int divideByZero = 5 / 0;
在这里,我们试图将一个数字除以 零。在这种情况下,会发生异常。因此,我们将此代码包含在 try
块中。
当程序遇到此代码时,会发生 ArithmeticException
。然后,异常会被 catch
块捕获,并执行 catch
块中的代码。
仅当 try
块中存在异常时,才会执行 catch
块。
注意:在 Java 中,可以在没有 catch
块的情况下使用 try
块。但是,不能在没有 try
块的情况下使用 catch
块。
Java try...finally 块
我们也可以将 try
块与 finally 块一起使用。
在这种情况下,无论 try 块中是否存在异常,finally 块始终会执行。
示例:Java try...finally 块
class Main {
public static void main(String[] args) {
try {
int divideByZero = 5 / 0;
}
finally {
System.out.println("Finally block is always executed");
}
}
}
输出
Finally block is always executed Exception in thread "main" java.lang.ArithmeticException: / by zero at Main.main(Main.java:4)
在上面的示例中,我们使用了带 finally 块的 try
块。我们可以看到 try
块中的代码会导致异常。
然而,无论是否有异常,finally
块中的代码都会执行。
Java try...catch...finally 块
在 Java 中,我们也可以在 try...catch
块之后使用 finally 块。例如,
import java.io.*;
class ListOfNumbers {
// create an integer array
private int[] list = {5, 6, 8, 9, 2};
// method to write data from array to a fila
public void writeList() {
PrintWriter out = null;
try {
System.out.println("Entering try statement");
// creating a new file OutputFile.txt
out = new PrintWriter(new FileWriter("OutputFile.txt"));
// writing values from list array to Output.txt
for (int i = 0; i < 7; i++) {
out.println("Value at: " + i + " = " + list[i]);
}
}
catch (Exception e) {
System.out.println("Exception => " + e.getMessage());
}
finally {
// checking if PrintWriter has been opened
if (out != null) {
System.out.println("Closing PrintWriter");
// close PrintWriter
out.close();
}
else {
System.out.println("PrintWriter not open");
}
}
}
}
class Main {
public static void main(String[] args) {
ListOfNumbers list = new ListOfNumbers();
list.writeList();
}
}
输出
Entering try statement Exception => Index 5 out of bounds for length 5 Closing PrintWriter
在上面的示例中,我们创建了一个名为 list 的数组和一个名为 output.txt 的文件。在这里,我们试图从数组中读取数据并将其存储到文件中。
请注意以下代码,
for (int i = 0; i < 7; i++) {
out.println("Value at: " + i + " = " + list[i]);
}
这里,数组的大小是 5
,数组的最后一个元素是 list[4]
。但是,我们试图访问 a[5]
和 a[6]
的元素。
因此,代码会生成一个异常,该异常会被 catch 块捕获。
由于 finally
块始终会执行,我们将关闭 PrintWriter
的代码包含在 finally 块中。
在 finally 块中包含重要的清理代码,如关闭文件或连接,是一种好的做法。
注意:在某些情况下,finally
块不会执行
- 使用
System.exit()
方法 - 在
finally
块中发生异常 - 线程死亡
多个 Catch 块
对于每个 try
块,可以有零个或多个 catch
块。多个 catch
块允许我们以不同的方式处理每个异常。
每个 catch
块的参数类型指示它可以处理的异常类型。例如,
class ListOfNumbers {
public int[] arr = new int[10];
public void writeList() {
try {
arr[10] = 11;
}
catch (NumberFormatException e1) {
System.out.println("NumberFormatException => " + e1.getMessage());
}
catch (IndexOutOfBoundsException e2) {
System.out.println("IndexOutOfBoundsException => " + e2.getMessage());
}
}
}
class Main {
public static void main(String[] args) {
ListOfNumbers list = new ListOfNumbers();
list.writeList();
}
}
输出
IndexOutOfBoundsException => Index 10 out of bounds for length 10
在此示例中,我们创建了一个大小为 10 的名为 arr
的整数数组。
由于数组索引从 0 开始,所以数组的最后一个元素是 arr[9]
。请注意语句,
arr[10] = 11;
这里,我们试图为一个索引 10 赋值。因此,会发生 IndexOutOfBoundException
。
当 try
块中发生异常时,
- 异常被抛给第一个
catch
块。第一个catch
块不处理IndexOutOfBoundsException
,因此将其传递给下一个catch
块。 - 上面的示例中的第二个
catch
块是合适的异常处理器,因为它处理IndexOutOfBoundsException
。因此,它被执行。
捕获多个异常
从 Java SE 7 及更高版本开始,我们现在可以使用一个 catch
块捕获多种类型的异常。
这减少了代码重复,并提高了代码的简洁性和效率。
catch
块可以处理的每个异常类型都用竖线 |
分隔。
其语法为
try {
// code
} catch (ExceptionType1 | Exceptiontype2 ex) {
// catch block
}
要了解更多信息,请访问 Java 捕获多个异常。
Java try-with-resources 语句
try-with-resources 语句是一个包含一个或多个资源声明的 try 语句。
其语法为
try (resource declaration) {
// use of the resource
} catch (ExceptionType e1) {
// catch block
}
资源是在程序结束时要关闭的对象。它必须在 try 语句中声明和初始化。
让我们举个例子。
try (PrintWriter out = new PrintWriter(new FileWriter("OutputFile.txt"))) {
// use of the resource
}
try-with-resources 语句也称为自动资源管理。该语句在语句结束时自动关闭所有资源。
要了解更多信息,请访问 Java try-with-resources 语句。