在Java中,运行时异常(RuntimeException)是一类不需要强制捕获的异常,它们通常是由程序错误引起的,如逻辑错误或不当的API使用。这些异常都是从 java.lang.RuntimeException
类继承而来。下面是一些常见的运行时异常:
-
NullPointerException - 当应用程序尝试使用 null 对象引用进行操作时抛出,例如调用 null 对象的实例方法、访问或修改 null 对象的字段、抛出 null 作为 Throwable 值。
String text = null; int length = text.length(); // 将抛出 NullPointerException
-
ArrayIndexOutOfBoundsException - 当数组被访问时使用了非法索引(负数或大于等于数组大小的数)时抛出。
int[] nums = {1, 2, 3}; int number = nums[3]; // 数组索引从0开始,3是一个非法索引,将抛出 ArrayIndexOutOfBoundsException
-
StringIndexOutOfBoundsException - 当尝试从字符串中访问索引时,如果该索引为负或大于等于字符串长度,则抛出。
String str = "hello"; char ch = str.charAt(5); // String 索引也是从0开始,5是非法索引,将抛出 StringIndexOutOfBoundsException
-
ArithmeticException - 当发生异常的算术条件时抛出,例如除以零。
int result = 10 / 0; // 除以零,将抛出 ArithmeticException
-
IllegalArgumentException - 当向方法传递了一个不合适的参数时抛出。
Thread t = new Thread(); t.setPriority(11); // 线程优先级的合法范围是 Thread.MIN_PRIORITY (1) 到 Thread.MAX_PRIORITY (10),这里将抛出 IllegalArgumentException
-
IllegalStateException - 在不适当的时间调用方法时抛出。
ArrayList<Integer> list = new ArrayList<>(); Iterator<Integer> it = list.iterator(); it.remove(); // 在调用 next() 之前调用 remove(),将抛出 IllegalStateException
-
ClassCastException - 尝试将对象强制转换为不是实例的类时抛出。
Object x = new Integer(0); System.out.println((String)x); // 尝试将 Integer 强制转换为 String,将抛出 ClassCastException
-
NumberFormatException - 尝试将字符串转换为数字格式,但字符串不具有适当的格式时抛出。
int num = Integer.parseInt("abc"); // 尝试将非数字字符串 "abc" 转换为整数,将抛出 NumberFormatException
这些运行时异常都是由程序员的错误引起的,通常可以通过更仔细地编写代码来避免。当处理这些异常时,最好查找并修复导致异常的根本原因,而不仅仅是捕获异常。