I've read in a couple of places that its better to catch exceptions higher up in the callstack but I havent been able to find the justification for this statement.
Scott Hanselman: Remember that Application_Error exists. Catch exceptions as high as you can, not as low.
I believe exception should be caught where it can be handled, high or low doesn't matter. Is it not true? If not then why?
Please add an example with your answer if possible.
Thanks
By catching an exception and allowing the code execution to continue, you are stating that you know how do deal with and circumvent, or fix a particular problem.
Catching by value makes a copy of the exception. But you don't rethrow the copy. You rethrow the original exception that was copied. As such, any modification to the exception caught by value will be lost, including the slicing.
You should catch the exception when you are in the method that knows what to do. For example, forget about how it actually works for the moment, let's say you are writing a library for opening and reading files. Here, the programmer knows what to do, so they catch the exception and handle it.
Exception Handling: It's a Good Thing. There is nothing wrong with the previous code. But overusing these patterns will cause code smells, and won't necessarily be beneficial. Likewise, misusing them can actually do a lot of harm to your code base, making it brittle, or obfuscating the cause of errors.
You should catch an exception at the point in the code where you can do something about it. Often, the code that generates the exception isn't in a position to deal with the problem, but the method that called that code, or the method that called the method that called that code, can handle the problem gracefully.
Say you've got some code that tries to open a file and read some data, and it generates an exception if the file doesn't exist. Code at that scope can't do much but bail, but several frames up the call stack a calling method might say "Oh, okay, got an exception. I'll try this alternate file instead" or "I guess that file didn't exist, so I'll go ahead and create a new one."
This is really one of the great benefits of exceptions: they free the developer from having to handle every possible error condition immediately. You can write code with the expectation that it's going to work most of the time, and your code doesn't need to be cluttered up with a lot of error handling. As long as you advertise which exceptions you might throw, you can make the code higher up in the call stack deal with problems in a way that's appropriate to whatever that code is trying to do.
I believe exception should be caught where it can be handled
Absolutely. The point is that lower in the callstack you are less likely to know how to handle it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With