Exception handling Groovy脚本中的主线程异常处理程序

Exception handling Groovy脚本中的主线程异常处理程序,exception-handling,groovy,Exception Handling,Groovy,Groovy有一个问题,若脚本中抛出了未捕获的异常,我需要在退出之前进行一些清理,但找不到一种方法 我已经尝试了Thread.setDefaultUncaughtExceptionHandler,但它似乎不适用于主线程。然后,我查看了堆栈跟踪,这使我找到了GroovyStarter,在那里我发现了一段很好的代码,这意味着Thread.setDefaultUncaughtExceptionHandler实际上不应该工作: public static void main(String args[])

Groovy有一个问题,若脚本中抛出了未捕获的异常,我需要在退出之前进行一些清理,但找不到一种方法

我已经尝试了Thread.setDefaultUncaughtExceptionHandler,但它似乎不适用于主线程。然后,我查看了堆栈跟踪,这使我找到了GroovyStarter,在那里我发现了一段很好的代码,这意味着Thread.setDefaultUncaughtExceptionHandler实际上不应该工作:

public static void main(String args[]) {
   try {
       rootLoader(args);
   } catch (Throwable t) {
       t.printStackTrace();
   }
}
出于示例的考虑,这里是我想要归档的内容(这不是可运行脚本,只是为了展示概念):

请不要建议使用try/catch,这是我能想到的:)

PS:我是Groovy的新手,因此可能缺少一些明显的东西。

你可以,当程序退出时,它将始终运行(如果可能):

def process = new ProcessBuilder(command).redirectErrorStream(true)

boolean success = false

def cleanup = {
    success = true
    process.destroy()
}

addShutdownHook {
    if(!success && process) {
        cleanup()
    }
}

process.start()
// alternatively, always rely on the shutdown hook
cleanup()
请注意,即使程序干净地退出,关闭钩子也会一直运行,因此,如果希望尽早清理连接,则需要有某种方法来跟踪已运行的清理

您还可以拥有任意数量的关闭挂钩,因此,如果您需要清理多个内容,可以在一个函数中使用它

def process = new ProcessBuilder(command).redirectErrorStream(true)

boolean success = false

def cleanup = {
    success = true
    process.destroy()
}

addShutdownHook {
    if(!success && process) {
        cleanup()
    }
}

process.start()
// alternatively, always rely on the shutdown hook
cleanup()