Why is it better to catch the exception above in callstack as soon as it can be handled?

I read in several places that it is better to catch the exceptions above in the callstack, but I could not find an excuse for this statement.

Scott Hanselman : Remember that Application_Error exists. Understand exceptions as low as possible.

I believe that an exception should be caught where it can be handled, high or low does not matter. Is that not so? If not, why?

Please add an example with your answer, if possible.

thanks

+6
exception-handling architecture
source share
3 answers

You have to catch the exception at the point in the code where you can do something. Often the code that throws the exception is unable to handle the problem, but the method that called this code, or the method called the method that called this code, can gracefully handle the problem.

Let's say you have code that tries to open a file and read some data, and it throws an exception if the file does not exist. The code in this area cannot do much, but a guarantee, but a few frames in the call stack, the calling method may say: โ€œOh, well, an exception has been thrown. Instead, I will try this alternative fileโ€ or โ€œI assume that this file was notโ€ , t exists, so I will continue and create a new one. "

This is really one of the big advantages of exceptions: they free the developer from having to handle all possible errors. You can write code with the expectation that it will work most of the time, and your code should not be cluttered with a lot of error handling. While you are advertising the exceptions that you can throw, you can make the code higher in the call stack by encountering problems in a way that goes well with everything that this code is trying to do.

+5
source share

I believe that an exception should be found where it can be handled

That's right. The fact is that below in the stop-kalk you are less inclined to know how to deal with it.

+1
source share

I think you should catch exceptions in two situations:

  • You know what to do with exception
  • You are exchanging an exception with another
0
source share

All Articles