简体   繁体   English

如果未选中 Java 则停止 bash 脚本 抛出异常

[英]Stop bash script if unchecked Java Exception is thrown

I am running a java program from within a Bash script.我正在从 Bash 脚本中运行 java 程序。 If the java program throws an unchecked exception, I want to stop the bash script rather than the script continuing execution of the next command.如果 java 程序抛出未经检查的异常,我想停止 bash 脚本而不是脚本继续执行下一个命令。

How to do this?这个怎么做? My script looks something like the following:我的脚本如下所示:

#!/bin/bash

javac *.java

java -ea HelloWorld > HelloWorld.txt

mv HelloWorld.txt ./HelloWorldDir

In agreement with Tom Hawtin,与汤姆·霍廷达成一致,

To check the exit code of the Java program, within the Bash script:要检查 Java 程序的退出代码,请在 Bash 脚本中:

#!/bin/bash 

javac *.java 

java -ea HelloWorld > HelloWorld.txt 

exitValue=$? 

if [ $exitValue != 0 ] 
then 
exit $exitValue 
fi 

mv HelloWorld.txt ./HelloWorldDir

Catch the exception and then call System.exit.捕获异常,然后调用 System.exit。 Check the return code in the shell script.检查 shell 脚本中的返回码。

#!/bin/bash

function failure()
{
    echo "$@" >&2
    exit 1
}

javac *.java || failure "Failed to compile"

java -ea HelloWorld > HelloWorld.txt || failure "Failed to run"

mv HelloWorld.txt ./HelloWorldDir || failure "Failed to move"

Also you have to ensure that java exits with a non-zero exit code, but that's quite likely for a uncaught exception.此外,您必须确保java以非零退出代码退出,但这很可能是未捕获的异常。

Basically exit the shell script if the command fails.如果命令失败,基本上退出 shell 脚本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM