Java 学习系列(4):Java 异常处理机制详解

Java 学习系列(4):Java 异常处理机制详解

1. 什么是异常?

在 Java 运行过程中,可能会发生各种错误,这些错误通常分为以下几种:

  • 语法错误(Syntax Errors):编译期错误,必须修正才能编译通过。
  • 逻辑错误(Logic Errors):程序逻辑问题,可能导致错误的计算结果。
  • 运行时错误(Runtime Errors):在程序运行过程中出现的异常情况,比如除零、数组越界、空指针等。

Java 通过 异常(Exception) 机制来捕获和处理运行时错误,以保证程序的稳定性。

2. Java 异常体系结构

Java 的异常体系结构如下:

Throwable
 ├── Error (错误,程序无法处理)
 └── Exception (异常,可捕获处理)
     ├── Checked Exception(受检异常,需要显式处理)
     └── Unchecked Exception(非受检异常,通常是 RuntimeException)
  • Error:如 OutOfMemoryError,表示 JVM 无法恢复的严重错误。
  • Exception:表示可处理的异常,如 IOExceptionSQLException
  • RuntimeException:如 NullPointerException,通常是代码逻辑错误。

3. Java 异常处理关键字

Java 提供了 try-catch-finally 语句用于异常捕获和处理:

try {
    // 可能发生异常的代码
} catch (ExceptionType e) {
    // 处理异常
} finally {
    // 可选,最终执行的代码(无论是否发生异常)
}

3.1 try-catch 处理异常

public class ExceptionHandlingExample {
    public static void main(String[] args) {
        try {
            int result = 10 / 0; // 触发 ArithmeticException
            System.out.println(result);
        } catch (ArithmeticException e) {
            System.out.println("发生算术异常: " + e.getMessage());
        }
    }
}

3.2 finally 语句

finally 语句块中的代码无论是否发生异常都会执行,通常用于释放资源。

import java.io.*;

public class FinallyExample {
    public static void main(String[] args) {
        FileInputStream fis = null;
        try {
            fis = new FileInputStream("test.txt");
            int data = fis.read();
            System.out.println("读取数据: " + data);
        } catch (IOException e) {
            System.out.println("发生 IO 异常: " + e.getMessage());
        } finally {
            try {
                if (fis != null) fis.close();
                System.out.println("文件流已关闭。");
            } catch (IOException e) {
                System.out.println("关闭文件时发生异常: " + e.getMessage());
            }
        }
    }
}

3.3 throws 关键字

如果一个方法可能抛出异常,可以使用 throws 关键字声明:

import java.io.*;

public class ThrowsExample {
    public static void readFile(String filePath) throws IOException {
        FileReader file = new FileReader(filePath);
        BufferedReader br = new BufferedReader(file);
        System.out.println(br.readLine());
        br.close();
    }

    public static void main(String[] args) {
        try {
            readFile("test.txt");
        } catch (IOException e) {
            System.out.println("文件读取异常: " + e.getMessage());
        }
    }
}

3.4 throw 关键字

throw 关键字用于手动抛出异常:

public class ThrowExample {
    public static void checkAge(int age) {
        if (age < 18) {
            throw new IllegalArgumentException("年龄必须大于 18!");
        }
        System.out.println("年龄符合要求。");
    }

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

4. 自定义异常

Java 允许开发者定义自己的异常类,通常继承 ExceptionRuntimeException

class CustomException extends Exception {
    public CustomException(String message) {
        super(message);
    }
}

public class CustomExceptionExample {
    public static void validate(int num) throws CustomException {
        if (num < 0) {
            throw new CustomException("数字不能为负数");
        }
        System.out.println("数字有效: " + num);
    }

    public static void main(String[] args) {
        try {
            validate(-5);
        } catch (CustomException e) {
            System.out.println("捕获自定义异常: " + e.getMessage());
        }
    }
}

5. 异常处理最佳实践

  1. 捕获具体异常,避免 catch (Exception e) 过度使用。
  2. 使用日志(如 Logger)记录异常,而不是 System.out.println()
  3. 避免过度使用 throws,应在合适的层级处理异常。
  4. 合理使用 finally 释放资源,或者使用 try-with-resources 语句。
  5. 不要忽略异常,即 catch (Exception e) {} 这样空的 catch 语句。

6. 总结

  • Java 提供了 try-catch-finally 结构用于异常处理。
  • throw 用于抛出异常,throws 用于声明异常。
  • Exception 分为 受检异常非受检异常
  • 可以 自定义异常 来满足特殊业务需求。

下一期:《Java 学习系列(5):Java 多线程编程》

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值