Java 异常处理

在上一个教程中,我们学习了 Java 异常。我们知道异常会异常地终止程序的执行。

因此,处理异常非常重要。以下是处理 Java 中异常的不同方法列表。

  • try...catch 块
  • finally 块
  • throw 和 throws 关键字

1. Java try...catch 块

try-catch 块用于处理 Java 中的异常。以下是 try...catch 块的语法

try {
  // code
}
catch(Exception e) {
  // code
}

在这里,我们将可能生成异常的代码放在 try 块中。每个 try 块后面都跟着一个 catch 块。

当发生异常时,它会被 catch 块捕获。catch 块不能在没有 try 块的情况下使用。

示例:使用 try...catch 进行异常处理

class Main {
  public static void main(String[] args) {

    try {

      // code that generate exception
      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

在示例中,我们尝试将一个数除以 0。这里的代码会生成一个异常。

为了处理异常,我们将代码 5 / 0 放入 try 块中。现在,当发生异常时,try 块中剩余的代码将被跳过。

catch 块捕获异常,并执行 catch 块内的语句。

如果 try 块中的任何语句都没有生成异常,则会跳过 catch 块。


2. Java finally 块

在 Java 中,无论是否发生异常,finally 块始终会执行。

finally 块是可选的。并且,对于每个 try 块,只能有一个 finally 块。

finally 块的基本语法是

try {
  //code
}
catch (ExceptionType1 e1) { 
  // catch block
}
finally {
  // finally block always executes
}

如果发生异常,finally 块将在 try...catch 块之后执行。否则,它将在 try 块之后执行。对于每个 try 块,只能有一个 finally 块。


示例:使用 finally 块进行 Java 异常处理

class Main {
  public static void main(String[] args) {
    try {
      // code that generates exception
      int divideByZero = 5 / 0;
    }

    catch (ArithmeticException e) {
      System.out.println("ArithmeticException => " + e.getMessage());
    }
    
    finally {
      System.out.println("This is the finally block");
    }
  }
}

输出

ArithmeticException => / by zero
This is the finally block

在上面的示例中,我们在 try 块中将一个数除以 0。这里的代码会生成一个 ArithmeticException

异常被 catch 块捕获。然后执行 finally 块。

注意:使用 finally 块是一个好习惯。因为它可以包含重要的清理代码,例如:

  • 可能会被 return、continuebreak 意外跳过的代码
  • 关闭文件或连接

3. Java throw 和 throws 关键字

Java throw 关键字用于显式地抛出单个异常。

当我们 throw 一个异常时,程序的流程会从 try 块转移到 catch 块。

示例:使用 Java throw 进行异常处理

class Main {
  public static void divideByZero() {

    // throw an exception
    throw new ArithmeticException("Trying to divide by 0");
  }

  public static void main(String[] args) {
    divideByZero();
  }
}

输出

Exception in thread "main" java.lang.ArithmeticException: Trying to divide by 0
        at Main.divideByZero(Main.java:5)
        at Main.main(Main.java:9)

在上面的示例中,我们使用 throw 关键字显式地抛出了 ArithmeticException

类似地,throws 关键字用于声明可能在方法内发生的异常类型。它用于方法声明。

示例:Java throws 关键字

import java.io.*;

class Main {
  // declareing the type of exception
  public static void findFile() throws IOException {

    // code that may generate IOException
    File newFile = new File("test.txt");
    FileInputStream stream = new FileInputStream(newFile);
  }

  public static void main(String[] args) {
    try {
      findFile();
    }
    catch (IOException e) {
      System.out.println(e);
    }
  }
}

输出

java.io.FileNotFoundException: test.txt (The system cannot find the file specified)

当我们运行此程序时,如果文件 test.txt 不存在,FileInputStream 会抛出 FileNotFoundException,它继承自 IOException 类。

findFile() 方法指定可以抛出 IOExceptionmain() 方法调用此方法并在抛出异常时对其进行处理。

如果方法不处理异常,那么其中可能发生的异常类型必须在 throws 子句中指定。

要了解更多信息,请访问 Java throw 和 throws

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战