Question

Is this good practice to wrap every function with try and catch?

I'm building a server in c#, and I'm trying to understand if one of the ways to make it more robust and protected from crashes is to wrap every function in it with try&catch statement.

Is this something reasonable to do??

Was it helpful?

Solution

Is this good practice to wrap every function with try and catch?

Absolutely not. That's a recipe for a disaster - it means you're likely to try to keep going with a request even if something has gone wrong and the state is corrupt.

Typically you should only have catch blocks where you can actually handle the exception and continue successfully; otherwise, you should let the exception bubble up. So you may want to have a catch block in order to retry certain operations, but only specific ones.

You may then have a catch block right at the top level, to stop the server itself from crashing. You haven't told us what sort of server you're building - the framework itself may provide an appropriate catch block like this.

The other reason to catch an exception is to wrap it and rethrow it as a more appropriate one to hide implementation details, and possibly to add more context. This can frankly be a bit of a pain though, and is only useful in certain situations. It really depends on what code is throwing the exception, and how you're expecting to deal with it.

OTHER TIPS

Two specific and important notes:

  1. Impersonation - always use try/catch/finally blocks: If you are ever using impersonation, you must always wrap your code in a try/catch/finally block, and put your log-out code in the finally block. The reason is that if an exception is thrown while impersonating, and the exception 'bubbles up', you will still be logged in as the impersonating identity, which is a security risk.

  2. Loops - never use try/catch blocks: try/catch blocks are expensive. If your application hits a roadblock for which the exception should bubble up to the top, that's fine, but never use try/catch within a loop to iterate to the next item. An example might be a loop that performs some calculation and you get a divide by 0 error if the data is bad. Rather than perform the calculation then catch the exception and continue the loop, just check for a 0 and continue to the loop so an exception is never thrown.

I think it's better to wrap group of functions in try and catch different exceptions and handle them. It provides more readable and smaller code with the same functionality

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top