简体   繁体   English

+e 与 e 在 throw Exception 中的区别

[英]Difference between +e vs , e in throw Exception

In Java, what is the difference between following 2 statements:在Java中,以下2个语句有什么区别:

throw new Exception ("msg" + e);

and

throw new Exception ("msg", e);

I know both of them are possible.我知道这两个都是可能的。 Is there any difference in how they work behind the scenes and which is a better practice to use?他们在幕后的工作方式有什么不同,哪种做法更好?

The first one creates a new exception with a message that is a string concatenation of msg and the string representation of e .第一个创建一个新的异常,消息是msg的字符串连接和e的字符串表示。 For this the toString method of e will be used.为此,将使用etoString方法。 This effectively gives the message of the original exception and concatenates it with the string msg .这有效地给出了原始异常的消息并将其与字符串msg连接起来。

The second one creates a new exception with only the message msg and adds the original exception as a cause.第二个创建一个只有消息msg的新异常,并将原始异常添加为原因。 Hence, more information from the original exception is available, for example the stack trace.因此,可以使用来自原始异常的更多信息,例如堆栈跟踪。

throw new Exception ("msg" + e); throws a new Exception with a message that's a concatenation of "msg" and e.toString() , losing e stacktrace in the process.抛出一个新的Exception一条消息,这是一个串联"msg"e.toString()失去e在这个过程中堆栈跟踪。

throw new Exception ("msg", e); throws a new Exception with a message "msg" and e as the cause.抛出一个带有消息"msg"e作为原因的新Exception

throw new Exception ("msg" + e); throws a new Exception with a message that's a concatenation of "msg" and e.toString() , losing e stacktrace in the process.抛出一个新的Exception ,其中包含一条由"msg"e.toString()串联而成的消息,在此过程中丢失e stacktrace。

throw new Exception ("msg", e); throws a new Exception with a message "msg" and e as the cause.抛出一个新的Exception ,消息为"msg" ,原因是e

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

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