开发者

Efficient Exception Handling in Java

How would you decide,开发者_StackOverflow when to throw an exception, and when to catch it?


"Efficiency" should not be a concern here.

You throw an exception when you run into a situation that your code cannot deal with (that you want the caller to do something about).

You catch an exception, when you can do something about it (and you may still want to re-throw it or another exception, if your caller should also do something about it as well).

Efficiency could be of interest when you are deciding whether to check for an error condition to avoid a subsequent exception or to just call some code and handle the exception afterwards. Here the rule of thumb is that exceptions should only occur in, well, exceptional cases, because they incur quite a bit of runtime overhead (when they are actually thrown, the pure presence of catch blocks has no cost).


Well this one of a highly debated topics where lot of people have strong opinions. Few useful links

http://www.ibm.com/developerworks/java/library/j-jtp05254.html

http://onjava.com/pub/a/onjava/2003/11/19/exceptions.html

Most of the popular frameworks like Spring believe in the philosophy of only handling exception if you can do something about them and therefore they throw more run time exceptions. This makes sense as throwing and catching checked exceptions is adding unnecessary code.

Still there is a catch. At some point in your application, especially closer to UI interface layer (e.g. servlets for you web application), you want to make sure you handle all kinds of exceptions properly and catch them. Otherwise user would see a 500 error, which definitely is not an ideal experience. At some point, you want to give user an idea of what went wrong. if its a run time exception, it might be better to say, unkown error, log it and send a mail to system administrator with the trace.

So yes, handle only exceptions which you expect and can process in a constructive way throughout the application. But make an exception to this rule when you are close to user interface layer of your application.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜