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?
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.
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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.