Groovy~Groovy的异常

方法使用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"
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值