方法使用try和catch关键字的组合捕获异常。try/catch块放置在可能生成异常的代码周围
class FirstTest{
static void main(String[] args) {
try {
// Protected code
} catch(ExceptionName e1) {
// Catch block
}
}
}
class FirstTest{
static void main(String[] args) {
try{
def arr = new int[3]
arr[5] = 5
} catch(Exception ex){
println "Catching the execption"
}
println "Let's move on after the exception"
}
}
class FirstTest{
static void main(String[] args) {
try{
def arr = new int[3]
arr[5] = 5
} catch (ArrayIndexOutOfBoundsException ex){
println "Catching the Array out of Bounds exception"
} catch (Exception ex){
println ("Catching the exception")
}
println ("Let's move on after the exception")
}
}
二、finally块
finally块在跟在try块或catch块之后。代码的finally块总是执行,而不管异常的发生。使用finally块可以运行任何你想要执行的清楚类型语句,无论在受保护代码中发生什么
try{
// Protected code
} catch (ExceptionType1 e1){
// Catch block
} catch (ExceptionType2 e2){
// Catch block
} catch (ExceptionType3 e3){
// Catch block
} finally {
// The finally block always executes
}
class FirstTest{
static void main(String[] args) {
try{
def arr = new int[3]
arr[5] = 5
} catch (ArrayIndexOutOfBoundsException ex){
println "Catching the Array out of Bounds exception"
} catch (Exception ex){
println "Catching the exception"
} finally {
println "The final block"
}
println "Let's move on after the exception"
}
}
三、异常方法
public String getMessage()
:返回有关已发生异常的详细信息public Throwable getCause()
:返回由Throwable对象表示的异常原因public String toString()
:返回与getMessage()的结果连接的类的名称public void pirntStackTrace()
:将toString()的结果与堆栈跟踪一起打印到System.err,错误输出流public StackTraceElement [] getStackTrace()
:返回包含堆栈跟踪上的每个元素的数组。索引0处的元素表示调用堆栈的顶部,数组中的最后一个元素表示调用堆栈底部的方法public Throwable fillInStackTrace()
:使用当前堆栈跟踪填充此Throwable对象的堆栈跟踪,添加到堆栈跟踪中的任何以前的信息
class FirstTest{
static void main(String[] args) {
try{
def arr = new int[3]
arr[5] = 5
} catch (ArrayIndexOutOfBoundsException ex){
println ex.toString()
println ex.getMessage()
println ex.getStackTrace()
} catch (Exception ex){
println "Catching the exception"
} finally {
println "The final block"
}
println "Let's move on after the exception"
}
}