Java

java runtimeexception代码示例有哪些

小樊
92
2024-11-25 04:53:34
栏目: 编程语言

Java运行时异常(RuntimeException)是在Java程序运行过程中可能遇到的异常情况,它们通常是由程序错误引起的,如数组越界、空指针引用等。以下是一些常见的Java运行时异常代码示例:

  1. 数组越界异常(ArrayIndexOutOfBoundsException)

    int[] arr = new int[5];
    System.out.println(arr[5]); // 抛出ArrayIndexOutOfBoundsException
    
  2. 空指针异常(NullPointerException)

    String str = null;
    System.out.println(str.length()); // 抛出NullPointerException
    
  3. 类型转换异常(ClassCastException)

    Object obj = "Hello";
    String str = (String) obj; // 抛出ClassCastException
    
  4. 索引越界异常(IndexOutOfBoundsException)

    List<String> list = Arrays.asList("A", "B", "C");
    System.out.println(list.get(3)); // 抛出IndexOutOfBoundsException
    
  5. 非法参数异常(IllegalArgumentException)

    int age = -5;
    if (age < 0) {
        throw new IllegalArgumentException("Age cannot be negative");
    }
    
  6. 数组初始化异常(NegativeArraySizeException)

    int[] arr = new int[-5]; // 抛出NegativeArraySizeException
    
  7. 空指针引用异常(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");
        }
    }
    
  8. 类型转换异常(ClassCastException)在集合中

    List<String> list = Arrays.asList("A", "B", "C");
    List<Integer> intList = (List<Integer>) list; // 抛出ClassCastException
    
  9. 非法访问异常(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);
        }
    }
    
  10. 未检查的转换异常(Unchecked cast exception)

    List<String> list = Arrays.asList("A", "B", "C");
    List<Integer> intList = (List<Integer>) list; // 编译器警告,运行时抛出ClassCastException
    

这些示例展示了Java运行时异常的一些常见情况。理解这些异常并采取适当的预防措施是编写健壮Java程序的关键。

0
看了该问题的人还看了