问题
Could you please tell me which approach is better in below two code blocks?
catch (MyException e) {
throw new MyException ("Error processing request", e);
}
Or
catch (MyException e) {
throw e;
}
回答1:
In order to compare two approaches, they should do the same thing. These two do not do the same thing.
The first approach would be better because you would change its message to a more user friendly one. Perhaps you could also log it (stacktrace or whatever...) before rethrowing it.
The second approach is better regarding performance. Actually, it would be even better if you did not catch the exception at all and let it throw it self.
You have to choose what is preferable, based on user experience and perhaps logging or performance. By default (and not always) I would choose the first.
Hope I helped!
回答2:
I do not see point in catching the exception and throwing it again. Once rare scenario could be that you need to perform some operation when the exception has occurred but at the same time report the exception to the caller to take appropriate action.
If this is the case then, first approach is better because you are just throwing the same exception again (instead of creating a new once). Btw, both the approaches will preserve the stack trace, just the case is that first one will avoid creation of unnecessary object.
Eg:
catch (MyException e) {
// May be perform some clean-up activity and throw
throw new MyException ("Error processing request", e);
}
回答3:
Preserve the inner exception, and I don't have an issue. Although, I don't think it makes sense to catch and then rethrow like that. Surely it would be better to just throw a custom-made exception?
回答4:
What ever the case you can keep StackTrace
, there is no issue. But it should be meanning full,there is no point catch and throw same Exception
.
回答5:
You can wrap the original exception like in your first option if you want to include any additional useful information for calling methods.
回答6:
The first one, because the second approach (rethrow the same exception without any processing) is useless.
Typically you need to define exception processing at start of project. Will you use checked or unchecked exceptions? Will you use standard or your custom exceptions? How will you use exception inheritance? Where will you process (log) exceptions? What are information to pass in exceptions. Once you answear such questions, then it is time to start building your API.
来源:https://stackoverflow.com/questions/20965712/catching-exception-and-throwing-the-same