Search code examples
c#visual-studiotry-catchrobust

C# - try and catch statement uses


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??


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.