debian

Debian Java异常处理机制

小樊
37
2025-12-14 21:07:43
栏目: 编程语言

Debian Java异常处理机制

一 核心机制与异常体系

二 在 Debian 上的实践步骤

三 代码示例与资源管理

示例代码

import java.io.*;

// 自定义异常
class InvalidAgeException extends Exception {
    public InvalidAgeException(String msg) { super(msg); }
}

public class ExceptionHandlingDemo {
    // 抛出与声明受检异常
    public static void checkAge(int age) throws InvalidAgeException {
        if (age < 18) throw new InvalidAgeException("Age must be >= 18");
    }

    public static void main(String[] args) {
        // 1) 基本 try-catch-finally
        try {
            int x = 10, y = 0;
            int z = x / y;
            System.out.println(z);
        } catch (ArithmeticException e) {
            System.err.println("Arithmetic error: " + e.getMessage());
        } finally {
            System.out.println("Cleanup in finally.");
        }

        // 2) 多重捕获
        try {
            int[] a = {1,2,3};
            System.out.println(a[5]);
        } catch (ArrayIndexOutOfBoundsException | IllegalArgumentException e) {
            System.err.println("Array or argument error: " + e.getMessage());
        }

        // 3) try-with-resources
        try (BufferedReader br = new BufferedReader(new FileReader("/etc/hostname"))) {
            String line;
            while ((line = br.readLine()) != null) System.out.println(line);
        } catch (IOException e) {
            System.err.println("IO error: " + e.getMessage());
        }

        // 4) 自定义异常 + 异常链
        try {
            checkAge(16);
        } catch (InvalidAgeException e) {
            // 包装为更高层业务异常并保留根因
            throw new RuntimeException("Business validation failed", e);
        }
    }
}

上述示例覆盖了 try-catch-finally、多重捕获、try-with-resources、throw/throws、自定义异常与异常链 的典型用法。

四 网络场景的异常处理要点

五 最佳实践与常见陷阱

0
看了该问题的人还看了