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<String> 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<String> list = Arrays.asList("A", "B", "C");
List<Integer> intList = (List<Integer>) 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<String> list = Arrays.asList("A", "B", "C");
List<Integer> intList = (List<Integer>) list; // 編譯器警告,運行時拋出ClassCastException
這些示例展示了Java運行時異常的一些常見情況。理解這些異常并采取適當的預防措施是編寫健壯Java程序的關鍵。