gpt4 book ai didi

java - 在 Java 中捕获 Perl 异常

转载 作者:行者123 更新时间:2023-12-01 22:43:25 24 4
gpt4 key购买 nike

我一直在尝试通过Java 运行Perl 脚本。我什至找到了如何执行此操作的脚本,但问题是我希望 Perl 抛出的异常在 Java 中返回。

import java.io.IOException;

public class Log {
public static void main(String[] args) throws IOException {
Process proc = null;
try
{
proc = Runtime.getRuntime().exec("perl C:\\Users\\myscript.pl");
int returncode = proc.exitValue();
System.out.println("Process Executed"+returncode);

}catch(Exception ae)
{

System.out.println("Exception is "+ae.toString());
}
finally
{
proc.destroy();
}
}
}

当我尝试运行此代码时,收到的异常是:

Exception is java.lang.IllegalThreadStateException: process has not exited

有人可以帮我吗?我做错了什么?

最佳答案

您需要在 exitValue() 之前调用 Process.waitFor()。我还强烈推荐阅读 When Runtime.exec() won't ,它有很多关于以更强大的方式调用外部进程的有用信息。

proc.waitFor();  // <======= blocks until process exit

int returncode = proc.exitValue();

System.out.println("Process Executed"+returncode)

Process.waitFor() 的文档

Causes the current thread to wait, if necessary, until the process represented by this Process object has terminated. This method returns immediately if the subprocess has already terminated. If the subprocess has not yet terminated, the calling thread will be blocked until the subprocess exits.

关于java - 在 Java 中捕获 Perl 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25736996/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com