Java throw案例如何手动抛出

wen java案例 21

本文目录导读:

Java throw案例如何手动抛出

  1. 基本语法
  2. 常见案例
  3. 注意事项
  4. 执行流程

在Java中,使用 throw 关键字可以手动抛出异常,以下是详细的使用方法和案例:

基本语法

throw new 异常类型("异常信息");

常见案例

参数合法性检查

public class Student {
    private String name;
    private int age;
    public void setAge(int age) {
        if (age < 0 || age > 150) {
            // 手动抛出 IllegalArgumentException
            throw new IllegalArgumentException("年龄必须在0-150之间,当前值:" + age);
        }
        this.age = age;
    }
    public static void main(String[] args) {
        Student student = new Student();
        try {
            student.setAge(200); // 会抛出异常
        } catch (IllegalArgumentException e) {
            System.out.println("错误:" + e.getMessage());
        }
    }
}

业务逻辑异常

public class BankAccount {
    private double balance;
    public void withdraw(double amount) {
        if (amount <= 0) {
            throw new IllegalArgumentException("取款金额必须大于0");
        }
        if (amount > balance) {
            // 自定义异常
            throw new InsufficientFundsException("余额不足,当前余额:" + balance);
        }
        balance -= amount;
    }
}
// 自定义异常类
class InsufficientFundsException extends RuntimeException {
    public InsufficientFundsException(String message) {
        super(message);
    }
}

强制检查型异常(Checked Exception)

import java.io.*;
public class FileProcessor {
    public void readFile(String path) throws FileNotFoundException {
        File file = new File(path);
        if (!file.exists()) {
            // 抛出检查型异常,方法必须声明 throws
            throw new FileNotFoundException("文件不存在:" + path);
        }
        // 继续处理文件...
    }
    public static void main(String[] args) {
        FileProcessor processor = new FileProcessor();
        try {
            processor.readFile("nonexistent.txt");
        } catch (FileNotFoundException e) {
            System.out.println("文件读取失败:" + e.getMessage());
        }
    }
}

链式异常(异常链)

public class DatabaseException extends Exception {
    public DatabaseException(String message, Throwable cause) {
        super(message, cause);
    }
}
public class DataAccess {
    public void queryDatabase() throws DatabaseException {
        try {
            // 模拟数据库操作
            int result = 10 / 0; // 产生 ArithmeticException
        } catch (ArithmeticException e) {
            // 将原始异常包装成自定义异常
            throw new DatabaseException("数据库查询失败", e);
        }
    }
}

自定义异常类的最佳实践

// 自定义运行时异常
public class ValidationException extends RuntimeException {
    private String field;
    private Object invalidValue;
    public ValidationException(String message, String field, Object invalidValue) {
        super(message);
        this.field = field;
        this.invalidValue = invalidValue;
    }
    public String getField() {
        return field;
    }
    public Object getInvalidValue() {
        return invalidValue;
    }
}
// 使用示例
public class UserValidator {
    public void validateEmail(String email) {
        if (email == null || !email.contains("@")) {
            throw new ValidationException(
                "无效的邮箱格式", 
                "email", 
                email
            );
        }
    }
}

注意事项

  1. 选择合适的异常类型

    • 使用现有的标准异常类(如 IllegalArgumentException
    • 或创建自定义异常类
  2. 提供有意义的异常信息

    • 包含出错原因
    • 包含相关的上下文信息
  3. 区分运行时异常和检查型异常

    • 运行时异常(继承 RuntimeException):不需要显式捕获
    • 检查型异常(继承 Exception):必须捕获或声明抛出
  4. 异常链的使用

    • 在捕获原始异常后,可以包装成新的异常抛出
    • 保持原始异常的堆栈信息

执行流程

正常执行 → 遇到 throw → 创建异常对象 → 方法立即结束 → 寻找匹配的 catch 块
                                         ↓
                              如果没有捕获 → 沿调用栈向上传播
                                         ↓
                              → 程序终止(未捕获的异常)

这样,throw 关键字让你能够精确控制程序的异常流程,在适当的时候中断正常执行并处理错误情况。

抱歉,评论功能暂时关闭!