这篇来介绍异常,异常在代码中是一定要接触和要写的代码块。
1.try catch
这个Java没什么不同,例如举例一个 10/0的运行时异常。
package com.anthony.test
try {
int i = 10 / 0
}catch (Exception e) {
println "发现异常:" + e
}
运行一下
发现异常:java.lang.ArithmeticException: / by zero
在catch 的小括号内,其实可以用ArithmeticException这个异常代替Exception,但是我们建议写Exception, 这个是所有异常的父类,任何异常都可以catch到,我们代码中,基本上都是用Exception。
关于异常的几个常用方法,例如一下三个,我们要会看得懂和使用。
package com.anthony.test
try {
int i = 10 / 0
}catch (Exception e) {
println "发现异常:" + e
println e.getCause()
println e.getMessage()
println e.printStackTrace()
}
2. try catch finally
package com.anthony.test
try {
int i = 10 / 0
}catch (ArithmeticException e1) {
println "捕获算术异常" + e1
}catch (Exception e) {
println "发现异常:" + e
println e.getCause()
println e.getMessage()
println e.printStackTrace()
} finally {
println "一定会执行到这里来"
}
增加了两点,第一点是catch的范围,第一个catch一般写比较精确的异常,如果这个精确异常捕获到了,后面的catch不好执行,这里涉及到异常类的范围。Exception类是所有异常类的父类,这个要知道。
第二点,finally代码块,不管异常是否发生,都会执行这块的代码。
3.try finally代码块
package com.anthony.test
try {
int i = 10 / 0
}finally {
println "一定会执行到这里来"
}
运行结果
一定会执行到这里来
Caught: java.lang.ArithmeticException: / by zero
java.lang.ArithmeticException: / by zero
at com.anthony.test.ExceptionHandling.run(ExceptionHandling.groovy:4)