Java 常見的運行時異常


1.ArrayIndexOutOfBoundsException索引越界異常

//數組越界異常java.lang.ArrayIndexOutOfBoundsException
        int[] arr = {1,2,3,4};
        System.out.println(arr[0]);
        System.out.println(arr[4]);//java.lang.ArrayIndexOutOfBoundsException

2.NullPointerException空指針異常

直接輸出沒有問題,但是調用其功能方法就會報異常。

        //空指針異常
        String name = null;
        System.out.println(name);//null
        System.out.println(name.length());//java.lang.NullPointerException

3.ClassCastException類型轉換異常

String轉Integer出錯

        //類型轉換異常
        Object o = "abc";
        Integer i = (Integer)o;//java.lang.ClassCastException

4.ArithmeticException數學操作異常

分母不能爲0

        //數學操作異常
        int a = 10/0;  //java.lang.ArithmeticException: / by zero
        System.out.println(a);

5.NumberFormatException數字轉換異常

        //數字轉換異常
        String a = "10aa";
        Integer integer = Integer.valueOf(a);
        System.out.println(integer);
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章