过早离开常规脚本的最佳方法是什么(system.exit(0) 除外)

2024-01-26

过早留下常规脚本的最佳方法是什么?

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

代码示例:

 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)
}

您可以使用退出状态代码来指示您遇到问题的线路。

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


这是一个幼稚的实现,如果行为空,则只会出现一个愚蠢的异常。

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)
        }
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

过早离开常规脚本的最佳方法是什么(system.exit(0) 除外) 的相关文章

随机推荐