architecture - Why is it better to catch exception high in the callstack rather as soon as it can be handled? -


I have read in some places that it is better to raise exceptions in the callstack, but I have been successful in doing this.

Scott Hanselman :

I believe an exception should be caught where it can be controlled, not high or low. . Is not that the truth? If not then why?

It is possible that you can add an example with your answer.

Thank you

You should catch an exception to the code at that point where you Regardless of what can be done about the problem, the code generating an exception is not in a position to deal with the problem, but the method used to call that code or the method called the method that is called that code is satisfactory Can handle in a manner.

Say you've got some code that tries to open a file and read some data, and if the file does not exist, it generates an exception. The code can not do much at that scope, but bail, but many frames above the call stack can call a calling method "Oh, well, an exception has been found." I would try this alternative file instead "or" I suppose That the file did this "T is present, so I will go ahead and build a new one. "

This is actually one of the great benefits of exceptions: they release the developer to handle the situation of all possible errors immediately. You can write the code with the expectation that most of the time , And your code does not need to be random with dealing with a lot of errors. By the time you tell that you can skip the exceptions, then you can call the code in the call stack deal kiss Can deal with problems that are trying to do, is suitable.

Comments