英文:
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 ("msg" + e);` throws a new `Exception` with a message that's a concatenation of `"msg"` and `e.toString()`, losing `e` stacktrace in the process.
`throw new Exception ("msg", e);` throws a new `Exception` with a message `"msg"` 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 ("msg" + e);` throws a new `Exception` with a message that's a concatenation of `"msg"` and `e.toString()`, losing `e` stacktrace in the process.
`throw new Exception ("msg", e);` throws a new `Exception` with a message `"msg"` and `e` as the cause.
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论