0

我有一个崩溃的 Java Virtual Mashines 没有错误消息的问题。我经常在我的代码中做一些检查。出了问题,如果其中一项检查无法完成,java 程序将无法继续。例如:

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

我可以确定,在使用 System.exit(-1) 杀死 JVM 之前,控制台上会打印一条带有 System.err.println("...") 的错误消息吗?如果不是,这可以解释为什么我的 JVM 崩溃而没有错误消息。

4

1 回答 1

1

System.out leads the output to the standard output stream (normally mapped to the console screen). System.err leads the output to the standard error stream (and, by default to the console). 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. Depend how to load a java program the error stream is not printed on console.

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:

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.

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:

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.

于 2020-08-08T18:20:11.627 回答