java 中 runtimeexception 的常见子类包括 nullpointerexception、indexoutofboundsexception、classcastexception、arithmeticexception 和 illegalargumentexception。这些异常在运行时抛出,通常由编程逻辑错误引起,如空指针访问、数组越界或类型转换失败。

NullPointerException 是如何触发的
当程序尝试使用 null 引用时,JVM 会抛出 NullPointerException。这通常发生在调用 null 对象的方法、访问其字段或获取数组长度的时候。

public class Main {
public static void main(String[] args) {
String str = null;
try {
int len = str.length();
} catch (NullPointerException e) {
System.out.println("Caught: " + e.getClass().getSimpleName());
}
}
}
运行结果:Caught: NullPointerException
立即学习“Java免费学习笔记(深入)”;
IndexOutOfBoundsException 的触发条件
当访问数组或集合的索引超出合法范围时,会抛出 IndexOutOfBoundsException。具体分为 ArrayIndexOutOfBoundsException(数组)和 StringIndexOutOfBoundsException(字符串)。

public class Main {
public static void main(String[] args) {
int[] arr = new int[5];
try {
int val = arr[5];
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Caught: " + e.getClass().getSimpleName());
}
}
}
运行结果:Caught: ArrayIndexOutOfBoundsException
ArithmeticException 的具体场景
算术运算中出现非法操作时抛出,最典型的是整数除以零。浮点数除以零不会抛出此异常,而是得到 Infinity 或 NaN。


















