What is the best alternative "On Error Resume Next" for C#?

Neel picture Neel · Jan 28, 2011 · Viewed 43k times · Source

If I put empty catch blocks for my C# code, is it going to be an equivalent for VB.NET's "On Error Resume Next" statement.

try
{
    C# code;
}

catch(exception)
{
}

The reason I am asking this is because I have to convert a VB.NET code to C#, and the old code has ~200 "On Error Resume Next" statements although I am using a proper try {} catch {} in my new code, but is there is a better alternative?

Answer

Tim Medora picture Tim Medora · Jan 28, 2011

I've found that VB programmers often littered code with many On Error Resume Next statements out of (bad) habit. My suggestion would be to start with no suppressed exceptions, and see what actually breaks. There may not be as many issues as you think. Conversely, the more regression testing you can do, the better; there may be some edge cases that only work when errors are ignored.

Ultimately, you need to decide on an error handling strategy, whether it is graceful unwinding inside many try/catch blocks, or letting errors percolate to a top-level handler (both strategies have their uses).

If you end up having to suppress some exceptions to meet a deadline, at the very least log those exceptions so that the next developer working on your code doesn't get burnt by an empty try/catch.