什么是过早离开常规脚本的最佳方法(system.exit(0)除外) [英] what is best way to leave a groovy script prematurely (except system.exit(0))

查看:87
本文介绍了什么是过早离开常规脚本的最佳方法(system.exit(0)除外)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是过早离开常规脚本的最佳方法?

what is best way to leave a groovy script prematurely ?

groovy脚本从给定的信息文件中读取一行,然后进行一些验证工作,以防验证失败(数据不一致),脚本需要过早离开流程.然后系统将再次调用该脚本以读取同一信息文件的下一行

A groovy script reads a row from a given info file then makes some verification work, in case of verification fails (inconsistent data) script needs to leave the flow prematurely . Then system will call the script again to read next row of the same info file

代码示例:

 read a row
 try{
   //make some verification here
 }catch(Exception e){
    logger("exception on something occurred "+e,e)
    //here need to leave a groovy script prematurely
 }

推荐答案

只需使用System.exit(0).

try {
    // code
} catch(Exception e) {
    logger("exception on something occurred "+e,e)
    System.exit(0)
}


您可以使用退出状态代码来指示遇到问题的那一行.


You could use the exit status code to indicate what line you had problems with.

零值表示一切正常,而正数表示行号.然后,您可以让groovy脚本将起始行作为输入参数.

A zero value would indicate that everything was OK, and a positive value would be the line number. You could then let your groovy script take the start line as an input parameter.

这是一个天真的实现,如果一行为空,则只有一个愚蠢的异常.

This is a naive implementation with just a silly exception if a line is empty.

file = new File(args[0])
startLine = args[1].toInteger()

file.withReader { reader ->
    reader.eachLine { line, count ->
        try {
            if (count >= startLine) {
                if (line.length() == 0) throw new Exception("error")
                println count + ': ' + line
            }
        } catch (Exception ignore) {
            System.exit(count)
        }
    }
}

这篇关于什么是过早离开常规脚本的最佳方法(system.exit(0)除外)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆