在抛出异常时,使用”+e”和”, e”之间的区别在于:

huangapple go评论69阅读模式
英文:

Difference between +e vs , e in throw Exception

问题

在Java中,以下两个语句有什么区别:

throw new Exception("msg" + e);

throw new Exception("msg", e);

我知道它们都是可能的。它们在背后的工作方式上有什么区别,哪种做法更好?

英文:

In Java, what is the difference between following 2 statements:

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?

答案1

得分: 4

throw new Exception("msg" + e);``` 抛出一个新的`Exception`,消息是`"msg"`和`e.toString()`的连接,这个过程中丢失了`e`的堆栈跟踪。

```plaintext
throw new Exception("msg", e);``` 抛出一个新的`Exception`,消息是`"msg"`,而`e`作为原因。


<details>
<summary>英文:</summary>

`throw new Exception (&quot;msg&quot; + e);` throws a new `Exception` with a message that&#39;s a concatenation of `&quot;msg&quot;` and `e.toString()`, losing `e` stacktrace in the process.

`throw new Exception (&quot;msg&quot;, e);` throws a new `Exception` with a message `&quot;msg&quot;` and `e` as the cause.

</details>



# 答案2
**得分**: 4

第一个方法创建一个新的异常,其消息是`msg`与`e`的字符串表示形式的连接。为此,将使用`e`的`toString`方法。这有效地提供了原始异常的消息,并将其与字符串`msg`连接起来。

第二个方法创建一个仅包含消息`msg`的新异常,并将原始异常添加为原因。因此,可以获得来自原始异常的更多信息,例如堆栈跟踪。

<details>
<summary>英文:</summary>

The first one creates a new exception with a message that is a string concatenation of `msg` and the string representation of `e`. For this the `toString` method of `e` will be used. This effectively gives the message of the original exception and concatenates it with the string `msg`.

The second one creates a new exception with only the message `msg` and adds the original exception as a cause. Hence, more information from the original exception is available, for example the stack trace.

</details>



# 答案3
**得分**: 0

```plaintext
throw new Exception("msg" + e);``` 抛出一个新的`Exception`,其中包含一个由`"msg"`和`e.toString()`连接而成的消息,此过程中丢失了`e`的堆栈跟踪信息。

```plaintext
throw new Exception("msg", e);``` 抛出一个新的`Exception`,消息为`"msg"`,并以`e`作为原因。


<details>
<summary>英文:</summary>

`throw new Exception (&quot;msg&quot; + e);` throws a new `Exception` with a message that&#39;s a concatenation of `&quot;msg&quot;` and `e.toString()`, losing `e` stacktrace in the process.

`throw new Exception (&quot;msg&quot;, e);` throws a new `Exception` with a message `&quot;msg&quot;` and `e` as the cause.

</details>



huangapple
  • 本文由 发表于 2020年9月7日 03:47:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/63768285.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定