printStackTrace()和toString()之间的区别 [英] Difference between printStackTrace() and toString()

查看:440
本文介绍了printStackTrace()和toString()之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很好奇printStackTrace()和toString()之间的区别。
乍一看,他们似乎做同样的事情。

I'm curious as to what the difference is between printStackTrace() and toString(). At first sight, they seem to do the exact same thing.

代码:

try {
// Some code
} catch (Exception e)
   e.printStackTrace();
   // OR
   e.toString()
}


推荐答案

不,有一个重要的区别!使用toString,您只能拥有异常类型和错误消息。使用printStackTrace()可以获得异常的整个堆栈跟踪,这对调试非常有帮助。

No, there is an important difference! Using toString, you only have the type of the exception and the error message. Using printStackTrace() you get the whole stacktrace of an exception, which is very helpful for debugging.

System.out.println(toString())示例:

Example of System.out.println(toString()):

java.io.FileNotFoundException: yourFile.txt (The system cannot find the file specified)

printStackTrace()示例:

Example of printStackTrace():

java.io.FileNotFoundException: yourFile.txt (The system cannot find the file specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.(FileInputStream.java:106)
at java.io.FileReader.(FileReader.java:55)
at ReadFromFile.main(ReadFromFile.java:14)

要创建整个堆栈跟踪的字符串,我通常使用此方法:

To make a string of the whole stacktrace, I usually use this method:

public static String exceptionStacktraceToString(Exception e)
{
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    PrintStream ps = new PrintStream(baos);
    e.printStackTrace(ps);
    ps.close();
    return baos.toString();
}

另请注意,只需调用 toString()只返回一个字符串,不会打印任何内容。

Also note that simply calling toString() simply returns a string, and won't print anything out.

这篇关于printStackTrace()和toString()之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆