简体   繁体   English

e.printStackTrace 和 System.out.println(e) 的区别

[英]Difference between e.printStackTrace and System.out.println(e)

Probably a newbie question, but everyone seems to use e.printStackTrace() , but I have always used System.out.println(e) when exception handling.可能是新手问题,但似乎每个人都使用e.printStackTrace() ,但我在异常处理时一直使用System.out.println(e) What is the difference and why is e.printStackTrace() preferable?有什么区别,为什么e.printStackTrace()更可取?

The output stream used is not the same as pointed out by @Brian, but the level of detail is not the same either - you can try with the simple test below.使用的输出流与@Brian 指出的不同,但详细程度也不相同 - 您可以尝试下面的简单测试。 Output:输出:

With println : you only know what exception has been thrown使用println :你只知道抛出了什么异常

java.lang.UnsupportedOperationException: Not yet implemented java.lang.UnsupportedOperationException:尚未实现

With printStackTrace : you also know what caused it (line numbers + call stack)使用printStackTrace :您还知道是什么原因造成的(行号 + 调用堆栈)

java.lang.UnsupportedOperationException: Not yet implemented java.lang.UnsupportedOperationException:尚未实现
at javaapplication27.Test1.test(Test1.java:27)在 javaapplication27.Test1.test(Test1.java:27)
at javaapplication27.Test1.main(Test1.java:19)在 javaapplication27.Test1.main(Test1.java:19)

public static void main(String[] args){
    try {
        test();
    } catch (UnsupportedOperationException e) {
        System.out.println(e);
        e.printStackTrace();
    }
}

private static void test() {
    throw new UnsupportedOperationException("Not yet implemented");
}

If you use System.out.println , then you're dumping your errors to the stdout , not stderr .如果您使用System.out.println ,那么您将错误转储到stdout ,而不是stderr

It's traditional to dump errors to standard error, so you can filter normal successful output from the error output.将错误转储到标准错误是传统的做法,因此您可以从错误输出中过滤出正常的成功输出。 It's a common practise for command-line utilities and consequently a good idea to follow.这是命令行实用程序的常见做法,因此是一个好主意。

eg例如

myCommand 2> /tmp/errors > /tmp/results

will write errors to one log, and the results to another.将错误写入一个日志,并将结果写入另一个。 Depending on your shell/invoking process etc. you can combine this info, throw errors away, react if any errors are thrown etc. See here for more info.根据您的外壳/调用过程等,您可以组合此信息、丢弃错误、在抛出任何错误时做出反应等。有关更多信息,请参见此处

Using printStackTrace() is a good idea since you're dumping out where the exception took place.使用printStackTrace()是一个好主意,因为您要转储异常发生的位置。 This is often invaluable for tracking errors that are unexpected since it'll give you a direct (if verbose) pointer to where exactly you ran into an error.这对于跟踪意外错误通常是无价的,因为它会给您一个直接(如果冗长)的指针,指向您遇到错误的确切位置。

System.out.println(e) is equivalent to System.out.println(e.toString()) : System.out is a PrintStream, PrintStream.println(Object o) calls PrintStream.println(o.toString()) . System.out.println(e)等价于System.out.println(e.toString())System.out是一个 PrintStream, PrintStream.println(Object o)调用PrintStream.println(o.toString())

e.toString() returns the name of the class, and the exception's getLocalizedMessage(). e.toString()返回类的名称,以及异常的 getLocalizedMessage()。

e.printStackTrace() writes that information to System.err (not System.out) and also a stack trace, that is, the chain of methods that led to the exception. e.printStackTrace()中写入该信息来System.err的(未System.out的),并且栈跟踪,即,导致该异常的方法的链。 This is useful information.这是有用的信息。

I've often thought it would be nice if there was a method that returns a String containing the info that's output by e.printStackTrace() .我经常认为,如果有一种方法可以返回一个包含e.printStackTrace()输出的信息的字符串,那就太好了。 Since there isn't you have to use e.getStackTrace() and write your own routine to output the resulting array of StackTraceElements.由于没有您必须使用e.getStackTrace()并编写您自己的例程来输出 StackTraceElements 的结果数组。

Since the output of e.printStackTrace();由于e.printStackTrace();的输出e.printStackTrace(); is System.err and usually I output my app log to a file, I recommend you to use both System.err and System.out to output errors.System.err并且通常我将我的应用程序日志输出到一个文件中,我建议您同时使用System.errSystem.out来输出错误。

public static void log(Exception e) {
    e.printStackTrace(); // This goes to System.err
    e.printStackTrace(System.out);
}

This way you can see the errors in the log file (in case you have one) and in the console.通过这种方式,您可以在日志文件(如果有的话)和控制台中看到错误。

System.out.println(e)不会为您提供堆栈跟踪,只会提供错误消息和异常类型,以及打印到标准输出而不是错误输出。

Bellow Program show the difference details波纹管程序显示差异细节

System.out.println(e); System.out.println(e); :- only showing the exception. :-只显示异常。 egjava.lang.ArithmeticException: / by zero e.printStackTrace(); egjava.lang.ArithmeticException: / by zero e.printStackTrace(); :- showing the details of exception and where to cause exception in program with line number eg java.lang.ArithmeticException: / by zero at test.Test.main(Test.java:7) :-显示异常的详细信息以及在程序中导致异常的位置,例如 java.lang.ArithmeticException: / 在 test.Test.main(Test.java:7) 处为零

package test;

public class Test {

    public static void main(String args[]) {
        try {
            System.out.println(12 / 0);

        } catch (Exception e) {
            System.out.println(e);
            e.printStackTrace();
        }

    }
}

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

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