Search code examples
exceptionerror-handlingtry-catch

Try Catch blocks inside or outside of functions and error handing


This is more a general purpose programming question than language specific. I've seen several approaches to try and catches.

One is you do whatever preprocessing on data you need, call a function with the appropriate arguments and wrap it into a try/catch block.

The other is to simply call a function pass the data and rely on try catches within the function, with the function returning a true/false flag if errors occurred.

Third is a combination with a try catch outside the function and inside. However if the functions try catch catches something, it throws out another exception for the try catch block outside the function to catch.

Any thoughts on the pros/cons of these methods for error control or if there is an accepted standard? My googling ninja skills have failed me on finding accurate data on this.


Solution

  • In general, an exception should only be caught if it can actually be handled.

    It makes no sense to catch an exception for no purpose other than to log it. The exception is that exceptions should be caught at the "top level" so that it can be logged. All other code should allow exceptions to propagate to the code that will log them.