[英]How can i handel exception of java -cp command in shell script(.sh file)
I put this command in .sh file: 我将此命令放在.sh文件中:
CP="$1"
"$JAVA_CMD" -cp "$CP" "$MAIN_CLASS" "$@"
Where CP is the path of the jar file 其中CP是jar文件的路径
my problem is: 我的问题是:
when CP does not have proper value, and in this instruction it could not find the main class and i will receive this exception: 当CP没有适当的值,并且在此指令中找不到主类,并且我将收到此异常:
Exception in thread "main" java.lang.NoClassDefFoundError
how can i handle this exception in shell script? 我该如何在Shell脚本中处理此异常?
Perhaps you may find this link helpful: http://www.tldp.org/LDP/abs/html/exit-status.html 也许您会发现此链接有用: http : //www.tldp.org/LDP/abs/html/exit-status.html
Bash contains a built-in variable called $?
Bash包含一个名为
$?
的内置变量$?
that contains the exit code of the previously executed command. 包含先前执行的命令的退出代码。
$? == 0
$? == 0
means the Java program has been executed successfully, and $? != 0
$? == 0
表示Java程序已成功执行,而$? != 0
$? != 0
means the Java program threw an exception such as the one in your case. $? != 0
表示Java程序抛出了一个异常,例如您所遇到的异常。
To replace any error printed to stderr with your own error message, you can suppress your command's stderr (by redirecting to /dev/null
) and print your message instead when your command's exit status is nonzero: 要将打印到stderr的任何错误替换为您自己的错误消息,可以取消命令的stderr(通过重定向到
/dev/null
),并在命令的退出状态为非零时打印消息,而不是:
CP="$1"
"$JAVA_CMD" -cp "$CP" "$MAIN_CLASS" "$@" 2>/dev/null || { echo "error: Java exited with nonzero status $?"; exit 1; }
A more verbose way to do this, which is probably more readable to folks relatively new to Bash: 一种更详细的方法,对于刚接触Bash的人来说可能更容易理解:
CP="$1"
if ! "$JAVA_CMD" -cp "$CP" "$MAIN_CLASS" "$@" 2>/dev/null; then
echo "error: Java exited with nonzero status $?"
exit 1
fi
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.