This week's giveaway is in the EJB and other Java EE Technologies forum. We're giving away four copies of EJB 3 in Action and have Debu Panda, Reza Rahman, Ryan Cuprak, and Michael Remijan on-line! See this thread for details.
1. If you know exactly what possible checked exception the code may get, then you should catch the specific exceptions, I understand it. But, I still don't see what's bad about putting "catch(Exception e)" at the end ? Just in case there is any exception you can't or don't list in your catch statements, at least you can catch it here. Some people may say it is not good to put so general exception catch, I agree. My point is, catch as many specfic checked exception as you can, then at the end , catch thise "Exception", what does it hurt ? please tell me.
2. Same question for catching "Runtime exception". Don't tell me people usually do it, tell me what it hurts. If I put this at the end, if there is real Runtime exception, at least I catch it and record the error details. I don't see it hurts anything, it just buy you more information. if you don't have this, when Runtime exception occurs you can't record any stack trace.
I know my idea may be very wrong, so please explain to me if you can. And tell me, if I don't catch "Exception" and "Runtime exception", then what if there is "Runtime exception" how do you record the information ? Similarly, what if there is some checked exception that you didn't list in your catch ?
FY Hsieh wrote:I still don't see what's bad about putting "catch(Exception e)" at the end?
Nothing is *fundamentally* wrong, but why bother? If you're already catching the thrown checked exceptions, why clutter the code? What if you need to pass uncaught exceptions up the chain? What if you're using declarative exception handling?
if you don't have this, when Runtime exception occurs you can't record any stack trace.
That's not true (in general): in a standalone application it'll get logged to the console. In a web app it'll usually get caught by the framework or container. I guess my comments are pretty much the same as above.
what if there is some checked exception that you didn't list in your catch ?
The code won't compile if a checked exception is neither caught nor declared to be thrown.
Joined: Aug 07, 2006
Thanks for the reply. Can I say
1. After I list as many specific exception in the 'catch" block and if the code passes compilation, then I should NEVER need to add an "catch(Exception e)" or "catch(Throwable e)" in the code ?
2. Same thing for "RuntimeException", just list as many specific exception in the 'catch" block and if the code passes compilation, then I should NEVER need to add an "catch(RuntimeException e)" in the code ?