《零基础学Java编程:手把手教你写出第一个可运行的程序 - 基础知识篇九》

目录

一 . 异常捕获

二 . 异常控制

        1.throw

        2.throws

3.throw和throws的区别

三 . 自定义异常

四 . assert关键字


一 . 异常捕获

(博哥有话说:出现异常不是打印台报错,是某一个调用本身就带异常,不抛出异常执行不了,抛出异常才能执行)

  1. 使用 try-catch 块捕获异常
  2. try 块包含可能抛出异常的代码
  3. catch 块处理特定类型的异常
  4. 可以有多重 catch 块,子类异常必须在前
  5. finally 块无论是否发生异常都会执行

(博哥有话说:异常处理机制分为捕获异常,抛出异常,处理异常)

public class ExceptionCatchDemo {
    public static void main(String[] args) {
        try {
            int[] numbers = {1, 2, 3};
            System.out.println(numbers[5]);  // 抛出ArrayIndexOutOfBoundsException
            int result = 10 / 0;  // 这行不会执行
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("数组越界异常: " + e.getMessage());
        } catch (ArithmeticException e) {
            System.out.println("算术异常: " + e.getMessage());
        } catch (Exception e) {
            System.out.println("通用异常处理: " + e.getMessage());
        } finally {
            System.out.println("finally块总是执行");
        }
        
        System.out.println("程序继续执行...");
    }
}

二 . 异常控制

(博哥有话说:未来我们学习IO流和数据库等会使用到,大家注意理解)

  1. 使用 throws 声明方法可能抛出的异常
  2. 调用方必须处理或继续抛出
  3. 运行时异常 (RuntimeException 及其子类) 不需要声明
  4. 检查型异常 (非 RuntimeException) 必须处理或声明
import java.io.*;

public class ExceptionControlDemo {
    // 声明可能抛出的检查型异常
    public static void readFile(String path) throws IOException {
        BufferedReader reader = new BufferedReader(new FileReader(path));
        String line = reader.readLine();
        System.out.println("文件内容: " + line);
        reader.close();
    }
    
    public static void main(String[] args) {
        try {
            readFile("nonexistent.txt");
        } catch (IOException e) {
            System.out.println("文件IO异常: " + e.getMessage());
        }
        
        // 运行时异常不需要声明
        int result = divide(10, 0);
    }
    
    public static int divide(int a, int b) {
        if (b == 0) {
            throw new ArithmeticException("除数不能为零");
        }
        return a / b;
    }
}

        1.throw

(博哥有话说:throw可以抛出任何类型的异常)

public class ThrowExample {
    
    // 检查年龄是否合法
    public static void checkAge(int age) {
        if (age < 0) {
            // 主动抛出自定义异常
            throw new IllegalArgumentException("年龄不能为负数");
        }
        if (age < 18) {
            // 抛出运行时异常
            throw new RuntimeException("未成年人禁止访问");
        }
        System.out.println("年龄合法: " + age);
    }

    public static void main(String[] args) {
        try {
            checkAge(-5);  // 会抛出IllegalArgumentException
        } catch (IllegalArgumentException e) {
            System.out.println("捕获到异常: " + e.getMessage());
        }
        
        checkAge(15);  // 会抛出RuntimeException,未捕获导致程序终止
    }
}

        2.throws

(博哥有话说:throws用于声明检查型异常)

import java.io.*;

public class ThrowsExample {
    
    // 声明可能抛出IOException
    public static void readFile(String path) throws IOException {
        FileReader file = new FileReader(path);
        BufferedReader reader = new BufferedReader(file);
        System.out.println(reader.readLine());
        reader.close();
    }
    
    // 声明可能抛出多个异常
    public static void processFile(String path) 
            throws FileNotFoundException, SecurityException {
        if (!path.endsWith(".txt")) {
            throw new SecurityException("仅允许.txt文件");
        }
        new FileInputStream(path);  // 可能抛出FileNotFoundException
    }

    public static void main(String[] args) {
        try {
            readFile("nonexistent.txt");  // 必须捕获或声明
        } catch (IOException e) {
            System.out.println("文件操作错误: " + e.getMessage());
        }
        
        try {
            processFile("data.csv");
        } catch (FileNotFoundException | SecurityException e) {
            System.out.println("处理文件失败: " + e.getMessage());
        }
    }
}

3.throw和throws的区别

特性throwthrows
作用主动抛出一个异常对象声明方法可能抛出的异常类型
位置方法体内使用方法声明处使用
数量一次只能抛出一个异常可以声明多个异常
语法throw new ExceptionType();throws ExceptionType1, ExceptionType2
用途显式触发异常警告调用者需要处理这些异常

三 . 自定义异常

  1. 继承 Exception 或 RuntimeException 创建自定义异常
  2. 通常提供多个构造方法
  3. 可以添加自定义字段和方法
  4. 检查型异常 vs 非检查型异常
// 自定义检查型异常
class InsufficientFundsException extends Exception {
    private double amount;
    
    public InsufficientFundsException(double amount) {
        super("资金不足,还差: " + amount);
        this.amount = amount;
    }
    
    public double getAmount() {
        return amount;
    }
}

// 自定义运行时异常
class InvalidAgeException extends RuntimeException {
    public InvalidAgeException(String message) {
        super(message);
    }
}

class BankAccount {
    private double balance;
    
    public BankAccount(double balance) {
        this.balance = balance;
    }
    
    public void withdraw(double amount) throws InsufficientFundsException {
        if (amount > balance) {
            throw new InsufficientFundsException(amount - balance);
        }
        balance -= amount;
    }
}

public class CustomExceptionDemo {
    public static void main(String[] args) {
        BankAccount account = new BankAccount(1000);
        
        try {
            account.withdraw(1500);
        } catch (InsufficientFundsException e) {
            System.out.println(e.getMessage());
            System.out.println("还需要: " + e.getAmount());
        }
        
        // 使用自定义运行时异常
        validateAge(15);
    }
    
    public static void validateAge(int age) {
        if (age < 18) {
            throw new InvalidAgeException("年龄必须大于18岁");
        }
    }
}

四 . assert关键字

(博哥有话说:assert意为断言,使用上就是判断对否,如果否JVM 会抛出 AssertionError 错误。)

assert 布尔表达式 : "错误消息";
  1. 用于程序内部调试
  2. 语法:assert condition; 或 assert condition : message;
  3. 默认不启用,需使用 -ea 参数开启
  4. 适用于不应该发生的情况检查
  5. 不应用于公共方法的参数验证
public class AssertDemo {
    public static void main(String[] args) {
        int age = 15;
        
        // 简单断言
        assert age >= 0;
        
        // 带消息的断言
        assert age >= 18 : "年龄必须大于等于18岁";
        
        System.out.println("年龄: " + age);
    }
    
    public static int calculateDiscount(int price, int discount) {
        // 使用断言检查内部状态
        int result = price - discount;
        assert result > 0 : "折扣后价格不能为负数";
        return result;
    }
}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

博哥爱学习

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值