Java运行时异常(RuntimeException)是在Java程序运行过程中可能遇到的异常情况,它们通常是由程序错误引起的,如数组越界、空指针引用等。以下是一些常见的Java运行时异常代码示例:
-
数组越界异常(ArrayIndexOutOfBoundsException):
int[] arr = new int[5]; System.out.println(arr[5]); // 抛出ArrayIndexOutOfBoundsException
-
空指针异常(NullPointerException):
String str = null; System.out.println(str.length()); // 抛出NullPointerException
-
类型转换异常(ClassCastException):
Object obj = "Hello"; String str = (String) obj; // 抛出ClassCastException
-
索引越界异常(IndexOutOfBoundsException):
List
list = Arrays.asList("A", "B", "C"); System.out.println(list.get(3)); // 抛出IndexOutOfBoundsException -
非法参数异常(IllegalArgumentException):
int age = -5; if (age < 0) { throw new IllegalArgumentException("Age cannot be negative"); }
-
数组初始化异常(NegativeArraySizeException):
int[] arr = new int[-5]; // 抛出NegativeArraySizeException
-
空指针引用异常(NullPointerException)在方法调用中:
public class Test { public static void main(String[] args) { Test test = null; test.someMethod(); // 抛出NullPointerException } public void someMethod() { System.out.println("This method is called"); } }
-
类型转换异常(ClassCastException)在集合中:
List
list = Arrays.asList("A", "B", "C"); List intList = (List ) list; // 抛出ClassCastException -
非法访问异常(IllegalAccessException):
class Test { private void someMethod() { System.out.println("This method is called"); } } public class Main { public static void main(String[] args) { Test test = new Test(); Method method = Test.class.getDeclaredMethod("someMethod"); method.setAccessible(true); // 允许访问私有方法 method.invoke(test); } }
-
未检查的转换异常(Unchecked cast exception):
List
list = Arrays.asList("A", "B", "C"); List intList = (List ) list; // 编译器警告,运行时抛出ClassCastException
这些示例展示了Java运行时异常的一些常见情况。理解这些异常并采取适当的预防措施是编写健壮Java程序的关键。