----java异常的体系结构
Throwable类包括两个子类:错误(Error)和异常(Exception)。他们的区别:Error是无法处理发错误,不可恢复。Exception可以通过改变程序而恢复。
--exception的分类:RuntimeException 和CheckedException。他们的区别:RuntimeException运行时异常,不会引起编译错误,不需要强制处理,checkedException会引起编译错误,需要强制处理。
--RuntimeException:ClassCastException、NullpointerException、ArithmeticException、IndexOutOfBoundsException.......。 --CheckedException:IOException、SqlException....。
----try-catch-finally的作用:
try:检测不安全的代码块(发现异常)
catch:异常处理代码
finally:不管出现或者不出现异常都会执行的代码
1.其中的catch和finally可以省略,但是try不能。2.catch的异常,父类的异常的catch块在子类异常之后。3.可以catch任何异常。4.catch CheckedException时,try块中必须存在可能引发该异常的代码,否则编译错误5.如果catch或者finally块中存在异常,则需要再次处理
----finally&return
1.是否出现异常都出执行finally。2.是否在正常代码和异常处理代码中return,仍然会先执行finally再return。3.不会执行finally的情况:System.exit(0)
----throw与throws
---throw用于抛出异常,抛出过后,使用try-catch捕获异常,再使用throws声明异常。
---throws方法同上。
public class throws1 {
public static void main(String[] args){
try{
test(120); //检测到异常
}
catch(IOException e){
e.printStackTrace(); //异常处理代码
}
}
public static void test(int age) throws IOException{ //抛出异常
throw new IOException(); //定义一个异常
}
}