RuntimeException 运行时异常:
派生于 RuntimeException 的异常,如被 0 除、数组下标越界、空指针等,其产生比较频繁,处理麻烦,如果显式的声明或捕获将会对程序可读性和运行效率影响很大。因此由系统自动检测并将它们交给缺省的异常处理程序。
编译器不处理RuntimeException,程序员需要增加“逻辑处理来避免这些异常”。
ArithmeticException异常:试图除以0
public class Test2{public static void main(String[] args){int b = 0;if(b != 0){System.out.println(1 / b);}}
}
NullPointerException异常:
public class Test3{public static void main(String[] args){String str = null;System.out.println(str.charAt(0));}
}
执行结果如图所示:
解决空指针异常,通常是增加非空判断:
public class Test3{public static void main(String[] args){String str = null;if(str != null){System.out.println(str.charAt(0));}}
}