Exception 类型
- 所有的异常都从
java.lang.Throwable
继承
- Exception class可以被分为三种类型 system errors, exception, runtime exceptions
-
Error: There is little you can do beyond notifying the user and trying to terminate the program gracefully. Example: LinkageError, VirtualMachineError
-
Exceptions: describes errors caused by your program and by external circumstances. Example: ClassNotFoundException, IOException,
-
Runtime Exceptions: describes programming errors, such as bad casting, accessing an out-of-bounds array, and numeric errors. Example: NullPointerException, IndexOutOfBoundsException
-
Unchecked Exception: 不用被强制的显式的抛出或者捕获, 包括 runtime exceptions, error 和它们的子类
In most cases, unchecked exceptions reflect programming logic errors that are unrecoverable. For example, NullPointerException
-
Checked Exception: 必须强制的被显式的抛出或者捕获(也就是使用try catch处理),其余的exception都为checked exception
使用Exception
声明 Exception
public void myMethod() throws Exception1
public void myMethod() throws Exception1, Exception2, ..., ExceptionN
抛出Exception
throw new IllegalArgumentException("Wrong Argument");
IllegalArgumentException ex = new IllegalArgumentException("Wrong Argument");
throw ex;
- 注意throw是抛出异常的时候用, throws是声明异常的时候用
Catch Exception
- Note: 在method2中,如果exception不是ex3,没有被catch住,则程序直接跳会method1,statment5和statment6都不会执行。
Throwable Class
使用 Throwable
Example
finally 关键字
- 不管有没有exception发生, finally总会被执行
- 如果try中出现exception则程序不会回到try中, 执行完finally之后会继续往下执行
- 即使在finally之前有return, finally里的代码还是会被执行
执行顺序 try - catch -finally
(假设try里有return)
- 如果没有exception发生: statement4会被执行, statement 5不会被执行
- 如果有exception 并且是 Exception 1, 则4和5都会被执行
- 如果有exception 并且不是 Exception 1, 则4会被执行, 然后程序报错
(假设try里没有return)
- 如果没有exception发生: statement4, statement 5都会被执行
- 如果有exception 并且是 Exception 1, 则4和5都会被执行
- 如果有exception 并且不是 Exception 1, 则4会被执行, 然后程序报错
- 没有exception: try和finally里都有return: 会使用finally里的return
- 有exception, try,catch, finally里都有return: 会执行finally里的return
总结:
- 如果finally里有return则一定会执行finally里的return
- 如果finally里没有return
- 没有exception的情况会执行try里的return, 如果try里没有return会继续finally之后的代码执行
- 有exception的情况会执行catch里的return,如果catch里没有return会继续finally之后的代码执行
在finally中修改变量
- finally相当于一个方法, 变量相当于参数, 所以遵循java值传递的规则
- 下图中finally没有影响tryli的变量
- 以下代码中finally中的put方法起作用了, 但是map = null没有起作用
Chained Exception
- Sometimes, you may need to throw a new exception (with additional information) along with the original exception. This is called chained exceptions.
自定义Exception