java常见的运行时异常总结

发表于: java/j2ee | 作者: | 日期: 2010/12/28 01:12

Runtime Exception,也就是我们所说的称运行时异常,是无需我们在代码中进行捕捉处理的,虚拟机取而代之,为我们进行了异常的处理。以下是我总结的几个比较常见的运行时异常。

NullPointerException:空指针异常类

示例:

package com.darkmi.basic;

public class Test {

public static void main(String[] args) {
System.out.println(toUpper(null));
}

public static String toUpper(String str){
return str.toUpperCase();
}

}

异常信息如下:

Exception in thread “main” java.lang.NullPointerException
at com.darkmi.basic.Test.toUpper(Test.java:11)
at com.darkmi.basic.Test.main(Test.java:6)

ArrayIndexOutOfBoundsException:数组下标越界异常

示例:

package com.darkmi.basic;

public class Test {

public static void main(String[] args) {
int[] a = {0,1,2,3};
System.out.println(a[4]);
}
}

异常信息如下:

Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException: 4
at com.darkmi.basic.Test.main(Test.java:7)

ArithmeticExecption:算术异常类:

示例:

package com.darkmi.basic;

public class Test {

public static void main(String[] args) {
int a = 10 / 0;
System.out.println(a);
}
}

异常信息如下:

Exception in thread “main” java.lang.ArithmeticException: / by zero
at com.darkmi.basic.Test.main(Test.java:6)

ClassCastException:类型强制转换异常

示例:

package com.darkmi.basic;
public class Test {

public static void main(String[] args) {
testParse(“aaa”);
}

public static void testParse(Object str){
Integer i = (Integer)str;
}
}

异常信息如下:

Exception in thread “main” java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer
at com.darkmi.basic.Test.testParse(Test.java:10)
at com.darkmi.basic.Test.main(Test.java:6)

: https://blog.darkmi.com/2010/12/28/1444.html

本文相关评论 - 才 2 条评论
2010-12-28 16:38:31

感谢分享

加个友情链接吧,呵呵,www.tonyxu.net

口哨
2010-12-30 15:08:09

顶~
不过有太多直接或间接继承RuntimeException类的了
比如 StringIndexOutOfBoundsException、ArrayIndexOutOfBoundsException 都是继承自IndexOutOfBoundsException
而在源代码中查找又不是很方便 这些确实需要系统的整理一下

Sorry, the comment form is closed at this time.