目录
一 . 异常捕获
(博哥有话说:出现异常不是打印台报错,是某一个调用本身就带异常,不抛出异常执行不了,抛出异常才能执行)
- 使用
try-catch块捕获异常 try块包含可能抛出异常的代码catch块处理特定类型的异常- 可以有多重
catch块,子类异常必须在前 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流和数据库等会使用到,大家注意理解)
- 使用
throws声明方法可能抛出的异常 - 调用方必须处理或继续抛出
- 运行时异常 (
RuntimeException及其子类) 不需要声明 - 检查型异常 (非
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的区别
| 特性 | throw | throws |
|---|---|---|
| 作用 | 主动抛出一个异常对象 | 声明方法可能抛出的异常类型 |
| 位置 | 方法体内使用 | 方法声明处使用 |
| 数量 | 一次只能抛出一个异常 | 可以声明多个异常 |
| 语法 | throw new ExceptionType(); | throws ExceptionType1, ExceptionType2 |
| 用途 | 显式触发异常 | 警告调用者需要处理这些异常 |
三 . 自定义异常
- 继承
Exception或RuntimeException创建自定义异常 - 通常提供多个构造方法
- 可以添加自定义字段和方法
- 检查型异常 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 布尔表达式 : "错误消息";
- 用于程序内部调试
- 语法:
assert condition;或assert condition : message; - 默认不启用,需使用
-ea参数开启 - 适用于不应该发生的情况检查
- 不应用于公共方法的参数验证
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;
}
}

被折叠的 条评论
为什么被折叠?



