Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is try wrapping excess code acceptable?

Tags:

c#

I was looking at some code that I am refactoring and notices the try ... catch code wraps quite a lot of code, not of all which would throw "normal" exceptions i.e. The code wouldn't throw at all or if it did it would be totally fatal exceptions like out of memory exceptions.

What I am wondering now is whether wrapping too much in try statements can cause any issues with performance?

So I see something like this:

try
{
    // Won't throw (I think that is the case anyway!)
    if (e.Error == null)
    {
        return;
    }

    // Only fatal exceptions
    myClass c = new myClass();

    // Now carry out the code that could cause catchable exception
}
catch
{
}
like image 809
Firedragon Avatar asked Nov 11 '11 14:11

Firedragon


1 Answers

Performance issues? Nothing that should be noticeable, really. From a bug hunting perspective, however, it can be a nightmare. When you wrap 100 lines of code in a try/catch its harder to figure out which of those 100 lines threw an exception. And despite all logic (or actually because of flawed human logic), code that "should never throw an exception" often throws the most.

I say, if you have code that should never throw an exception then back it up by not wrapping it in a try/catch block. Otherwise just try/catch your Main method and be done with it.

like image 195
Chris Haas Avatar answered Oct 01 '22 08:10

Chris Haas