首页 文章

什么是过早保留groovy脚本的最佳方法(system.exit(0)除外)

提问于
浏览
29

什么是过早留下时髦脚本的最佳方法?

一个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
 }

4 回答

  • 22

    我很确定你可以从脚本中找到 return .

  • 20

    只需使用 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)
            }
        }
    }
    
  • 2

    只需使用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
     }
    
  • 0

    使用return 0

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

相关问题