一 什么是编译时异常,什么是运行时异常
运行时异常可以通过改变程序避免这种情况发生,比如,除数为0异常,可以先判断除数是否是0,如果是0,则结束此程序。从继承上来看,只要是继承RunTimeException类的,都是运行时异常,其它为编译时异常。
二编译时异常和运行时异常的区别
使用抛出处理方式处理异常时,对于编译时异常,当函数内部有异常抛出,该函数必须声明,调用者也必须处理,运行时异常则不一定要声明,调用者也不必处理;
ArithmeticException运行时异常
打印结果:
Exception in thread "main" java.lang.ArithmeticException
at testexception.Test.test(Test.java:11)
at testexception.Test.main(Test.java:7)
at testexception.Test.test(Test.java:11)
at testexception.Test.main(Test.java:7)
从上面代码中可以看出,运行时异常可以不需声明异常
下面是编译时异常,TimeOutException,超时连接异常,模拟当i大于10时,即超过10秒,抛出连接超时异常。
Exception in thread "main" java.util.concurrent.TimeoutException
at testexception.Test.test(Test.java:12)
at testexception.Test.main(Test.java:8)
at testexception.Test.test(Test.java:12)
at testexception.Test.main(Test.java:8)
从上面可以看出,编译时异常必须在函数中声明,调用者也必须在函数中处理.