运行时异常RuntimeException:
例如:空指针异常,数组越界异常,算术异常(除数为0)等等,一般都是由程序员的疏忽造成的。
对于运行时异常和Error,不是由程序员捕获,而是由jvm捕获和抛出,但是对于剩下的非运行时异常,则必须由程序员捕获和处理(自行处理还是抛出)
if(t==null){
throw new NullPointerException();
}
我们不希望所有使用对象t之前都包含以上代码,所以这类运行时异常时可以不按照传统的异常处理机制:写入try-catch或者声明时抛出throws。
例如以下代码:
- public class TestException {
- public static void main(String[] args) {
- TestException te = new TestException();
- te.f1();
- System.out.println("main");
- }
- void f1(){
- f2();
- System.out.println("f1");
- }
- void f2() {
- f3();
- System.out.println("f2");
- }
- void f3(){
- throw new RuntimeException();
- }
- }
- output:
- Exception in thread "main" java.lang.RuntimeException
- at TestException.f3(TestException.java:24)
- at TestException.f2(TestException.java:18)
- at TestException.f1(TestException.java:11)
- at TestException.main(TestException.java:5)