简体   繁体   English

Java 中 System.exit(-1) 之前的 System.err.println() 错误消息

[英]Error Message with System.err.println() before System.exit(-1) in Java

I have a problem with crashed Java Virtual Mashines without error message.我遇到了 Java Virtual Mashines 崩溃的问题,没有错误消息。 I often do some checks in my code.我经常在我的代码中做一些检查。 Something went wrong, if one of these checks will not be fulfilled and the java program shall not carry on.出现问题,如果其中一项检查无法完成,java 程序将无法继续。 EG:例如:

if(!constraint){
   System.err.println("The constraint is not fullfilled!");
   System.exit(-1);
}

Can I be sure, that an error message with System.err.println("...") is printed on the console before the JVM is killed with System.exit(-1)?我可以确定,在 JVM 被 System.exit(-1) 杀死之前,控制台上会打印一条带有 System.err.println("...") 的错误消息吗? If not, this could explain why my JVM crashes without error message.如果不是,这可以解释为什么我的 JVM 崩溃而没有错误消息。

System.out leads the output to the standard output stream (normally mapped to the console screen). System.out 将 output 引导至标准 output stream(通常映射到控制台屏幕)。 System.err leads the output to the standard error stream (and, by default to the console). System.err 将 output 引导至标准错误 stream (并且默认为控制台)。 The idea behind having these two is that the standard output should be used for regular program output, and standard error should be used for error messages.拥有这两个的想法是标准 output 应该用于常规程序 output,标准错误应该用于错误消息。 Depend how to load a java program the error stream is not printed on console.取决于如何加载 java 程序错误 stream 未打印在控制台上。

Both the streams can be redirected to different destinations.两个流都可以重定向到不同的目的地。 If it is desired to redirect the output to an output file and error messages to a different log file, than on UNIX it can be done as follows:如果希望将 output 重定向到 output 文件并将错误消息重定向到不同的日志文件,则可以执行以下操作:

java MyClass > output.log 2>error.log

This causes the regular output (using System.out) to be stored in output.log and error messages (using System.err) to be stored in error.log.这会导致常规 output(使用 System.out)存储在 output.log 中,错误消息(使用 System.err)存储在 error.log 中。

Another option is in your code redirect the outputs:另一个选项是在您的代码中重定向输出:

PrintStream outStream = new PrintStream(new File("outFile.txt"));
System.setOut(outStream);
System.out.println("This is a baeldung article");

And in case of System.err:在 System.err 的情况下:

PrintStream errStream = new PrintStream(new File("errFile.txt"));
System.setErr(errStream);
System.err.println("This is a baeldung article error");

The System.out and System.err is not a better solution to check this, I suggest to add a logger like SL4J to log this in appropriate file or output. System.out 和 System.err 不是检查这个的更好的解决方案,我建议添加一个像 SL4J 这样的记录器来将这个记录到适当的文件或 output 中。

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

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