提前离开groovy脚本的最佳方式是什么(system.exit(0)除外)



过早地离开groovy脚本的最佳方式是什么?

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

我很确定您可以从脚本中只return

只需使用return:

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

使用return0

 read a row
 try{
   //make some verification here
 }catch(Exception e){
    logger("exception on something occurred "+e,e)
    return 0;
 }

最新更新