##1.NullPointerException: Null pointer exception
Example:public static void main(String[] args) { String str = null; //此处报空指针异常 System.out.println(str.length()); }
Exception in thread "main" java.lang.NullPointerException at cn.com.gjw.MyClass.main(MyClass.java:7)
2.ClassCastException: Type cast exception
Example: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 cn.com.gjw.MyClass.main(MyClass.java:7)
3.ArrayIndexOutOfBoundsException: Array subscript out-of-bounds exception
Example:public static void main(String[] args) { int arr[] = {1,2}; // 此处报数组下标越界异常 System.out.println(arr[2]); }
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2 at cn.com.gjw.MyClass.main(MyClass.java:7)
4.ArithmeticException : Arithmetic operation exception
Example:public static void main(String[] args) { // 整数0做了分母,报算术运算异常 System.out.println(1 / 0); }
Exception in thread "main" java.lang.ArithmeticException: / by zero at cn.com.gjw.MyClass.main(MyClass.java:6)
5.NumberFormatException: Number format exception
Example:public static void main(String[] args) { // 将字符串“it”转换为Integer类型的,当然会报数字格式异常啦 System.out.println(Integer.parseInt("it")); }
Exception in thread "main" java.lang.NumberFormatException: For input string: "it" at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) at java.lang.Integer.parseInt(Integer.java:492) at java.lang.Integer.parseInt(Integer.java:527) at cn.com.gjw.MyClass.main(MyClass.java:6)
The above is the detailed content of Several common exceptions in java. For more information, please follow other related articles on the PHP Chinese website!