java几种常见运行时异常及简单例子

java几种常见运行时异常及简单例子

1、java.lang.IndexOutOfBoundsException
public static void main(String[] args) {
    ArrayList<String> list = new ArrayList<String>();
    list.get(0);
}
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
    at java.util.ArrayList.rangeCheck(ArrayList.java:653)
    at java.util.ArrayList.get(ArrayList.java:429)
    at test.demo.ExceptionCheck.main(ExceptionCheck.java:9)

2、java.lang.NullPointerException
public static void main(String[] args) {
        ArrayList<String> list = null;
        System.out.println(list.get(0));
    }
Exception in thread "main" java.lang.NullPointerException
    at test.demo.ExceptionCheck.main(ExceptionCheck.java:9)

3、java.lang.ArithmeticException
public static void main(String[] args) {
    int dividend = 1;
    int divisor = 0;
    System.out.println(dividend / divisor);
}
Exception in thread "main" java.lang.ArithmeticException: / by zero
    at test.demo.ExceptionCheck.main(ExceptionCheck.java:10)

4、java.lang.NumberFormatException
public static void main(String[] args) {
    String source = "123s";
    Integer result = new Integer(source);
    System.out.println(result.intValue());
}
Exception in thread "main" java.lang.NumberFormatException: For input string: "123s"
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.lang.Integer.parseInt(Integer.java:580)
    at java.lang.Integer.<init>(Integer.java:867)
    at test.demo.ExceptionCheck.main(ExceptionCheck.java:9)

5、java.lang.ClassCastException
public static void main(String[] args) {
    Object x = new String("String");
    System.out.println((Integer) x);
}
Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer
    at other.demo.ExceptionCheck.main(ExceptionCheck.java:7)

6、java.lang.ArrayStoreException
public static void main(String[] args) {
    List<Integer> list = new ArrayList<Integer>();
    list.add(12);
    list.add(13);

    list.toArray(new Long[list.size()]);
}
Exception in thread "main" java.lang.ArrayStoreException
    at java.lang.System.arraycopy(Native Method)
    at java.util.ArrayList.toArray(ArrayList.java:408)
    at other.demo.ExceptionCheck.main(ExceptionCheck.java:13)
发布了46 篇原创文章 · 获赞 10 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/sqhren626232/article/details/103352108