编程自学指南:java程序设计开发,Java RuntimeException 详解课件(初学者版)
一、课程信息
学习目标
- 理解 RuntimeException 的核心特性:非受检异常
- 掌握 10 + 常见 RuntimeException 的触发场景
- 能通过代码预防和处理运行时异常
- 区分 RuntimeException 与受检异常的处理差异
二、课程导入:程序中的 "隐形炸弹"
🌰 生活类比
- 受检异常:像开车前检查油表(必须处理)
- RuntimeException:像开车时突然爆胎(非预期但可能发生)
三、RuntimeException 核心特性
🔍 1. 定义与继承树
继承结构:
Throwable
↳ Exception
↳ RuntimeException(运行时异常)
↳ 受检异常(如IOException)
↳ Error(错误,不可恢复)
特性:
✅ 非受检异常(编译器不强制处理)
✅ 通常由程序逻辑错误引起
🔧 2. 与受检异常对比
特性 | RuntimeException | 受检异常(如 IOException) |
---|---|---|
处理要求 | 无需强制捕获 | 必须用try-catch 或throws |
发生原因 | 逻辑错误(如空指针) | 外部条件(如文件不存在) |
修复方式 | 修改代码逻辑 | 处理外部条件 |
四、常见 RuntimeException 案例
🔥 案例 1:NullPointerException(空指针)
触发场景:调用null
对象的方法或属性
public class NPEExample {
public static void main(String[] args) {
String str = null;
System.out.println(str.length()); // 抛出NPE
}
}
预防方法:
if (str != null) { // 判空检查
System.out.println(str.length());
}
🔥 案例 2:ArrayIndexOutOfBoundsException(数组越界)
触发场景:访问不存在的数组索引
public class ArrayIndexExample {
public static void main(String[] args) {
int[] arr = {1, 2, 3};
System.out.println(arr[3]); // 索引3超出范围(0-2)
}
}
预防方法:
if (index >= 0 && index < arr.length) { // 检查索引范围
System.out.println(arr[index]);
}
🔥 案例 3:ClassCastException(类型转换异常)
触发场景:强制转换不兼容的类型
public class ClassCastExample {
public static void main(String[] args) {
Object obj = new Integer(10);
String str = (String) obj; // Integer无法转String
}
}
预防方法:
if (obj instanceof String) { // 类型检查
String str = (String) obj;
}
🔥 案例 4:ArithmeticException(算术异常)
触发场景:除以 0
public class ArithmeticExample {
public static void main(String[] args) {
int result = 10 / 0; // 抛出ArithmeticException
}
}
预防方法:
if (divisor != 0) { // 除数判零
int result = dividend / divisor;
}
🔥 案例 5:IllegalArgumentException(非法参数)
触发场景:方法接收到非法参数
public class IllegalArgumentExceptionExample {
public static void printPositive(int num) {
if (num < 0) {
throw new IllegalArgumentException("参数不能为负数");
}
System.out.println(num);
}
public static void main(String[] args) {
printPositive(-5); // 抛出异常
}
}
五、RuntimeException 处理策略
✅ 最佳实践 1:预防为主
策略:通过条件判断避免异常发生
案例:避免空指针
// 反模式
String result = str.toUpperCase(); // 可能NPE
// 最佳实践
String result = (str != null) ? str.toUpperCase() : "";
✅ 最佳实践 2:选择性捕获
场景:在关键流程中捕获异常
public class LoginService {
public void login(String username, String password) {
try {
validate(username, password); // 可能抛异常
// 登录逻辑
} catch (IllegalArgumentException e) {
System.out.println("登录失败:" + e.getMessage());
}
}
}
⚠️ 反模式:过度捕获
错误做法:
try {
// 所有代码
} catch (RuntimeException e) {
// 不处理或简单打印
}
危害:隐藏程序逻辑错误,增加调试难度
六、课堂练习
练习 1:修复空指针异常
任务:
public static void printLength(String str) {
System.out.println(str.length()); // 可能NPE
}
练习 2:处理非法年龄
需求:
- 定义
setAge(int age)
方法,年龄必须 > 0 且 < 150 - 否则抛出
IllegalArgumentException
七、课程总结
知识图谱:
RuntimeException
↳ 特性:非受检,由逻辑错误引起
↳ 常见类型:NPE、数组越界、类型转换等
↳ 处理策略:预防为主,选择性捕获
口诀记忆:
“运行时异常不用慌,逻辑错误是根源,
空指针前先判空,数组越界查索引,
类型转换先检查,算术运算防除零,
非法参数早抛出,程序健壮又安全!”
八、课后作业
必做 1:分析异常原因
代码:
List<String> list = new ArrayList<>();
list.add("Java");
System.out.println(list.get(1)); // 抛出何异常?为什么?
必做 2:实现用户注册校验
需求:
register(String username, String password)
方法- 用户名长度需 3-20 位,密码需 6-16 位
- 否则抛出
IllegalArgumentException