如何使用try-catch-finally语句处理异常?

q1871901600 发布于 2024-11-19 22 次阅读


try块包含可能会抛出异常的代码,catch块捕获并处理特定类型的异常,finally块无论是否抛出异常都会执行。

public class TryCatchFinallyExample {
    public static void main(String[] args) {
        try {
            // 尝试执行可能会抛出异常的代码
            performOperation();
        } catch (ArithmeticException e) {
            // 如果发生算术异常,例如除以零,则捕获并处理它
            System.out.println("An arithmetic error occurred: " + e.getMessage());
        } catch (Exception e) {
            // 捕获其他所有类型的异常
            System.out.println("An unexpected error occurred: " + e.getMessage());
        } finally {
            // 无论是否抛出异常,都会执行finally块中的代码
            System.out.println("This is always executed, regardless of an exception.");
        }
    }

    public static void performOperation() throws ArithmeticException {
        int result = 10 / 0; // 这里会抛出ArithmeticException
        System.out.println("Result is: " + result);
    }
}

在这个例子中:

  • try块包含了可能会抛出异常的代码。在这个例子中,performOperation方法可能会抛出ArithmeticException
  • catch块捕获并处理特定类型的异常。这里有两个catch块:第一个专门处理ArithmeticException,第二个处理所有其他类型的Exception
  • finally块无论是否抛出异常都会执行。在这个例子中,它用于打印一条消息,表明finally块已经被执行。

这个结构确保了即使在发生异常的情况下,也能执行一些清理工作,比如关闭文件流、释放资源等。finally块是可选的,但通常推荐使用,因为它提供了一种确保执行清理代码的方法。

一个会写python的Java工程师
最后更新于 2024-11-19