Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I avoid exceptions in C#, continuing code execution?

I have the following C# code. Whenever an exception is caught, say at line 1, I am never able to reach other lines (2, 3, 4, etc).

try
{
    line1
    line2
    ...
}
catch (Exception ex)
{
    ...
}

Is it possible, in C#, to say that if line 1 generates an exception, just continue on to the other lines (2, 3, 4, etc)?

like image 327
asel Avatar asked Oct 13 '09 14:10

asel


3 Answers

Exceptions should not be ignored. :)
They exists and are thrown for a reason: an exceptional situation has occured, a certain condition is not met, and I cannot continue working ...

It is possible to ignore exceptions, if you put a try / catch block around each line of code, but I don't think that you really want to do that ...

like image 75
Frederik Gheysels Avatar answered Oct 15 '22 19:10

Frederik Gheysels


You could create a SkipOnError method like this:

private SkipOnError(Action action)
{
    try 
    {
        action();
    }
    catch
    {
    }
}

Then you could call it like so:

try
{ 
    SkipOnError(() => /*line1*/);
    line2;
    line3;
} catch {}

Edit: This should make it easier to skip a given exception:

private SkipOnError(Action action, Type exceptionToSkip)
{
    try 
    {
        action();
    }
    catch (Exception e)
    {
        if (e.GetType() != exceptionToSkip) throw;            
    }
}

NOTE: I'm not actually suggesting you do this - at least not on a regular basis, as I find it rather hacky myself. But it does sort of show off some of the functional things we can now do in C#, yay!

What I would really do is this: Refactor line1 into a method (Extract Method). That new method should handle any foreseeable exceptions (if they can be handled) and thus leave the caller in a known state. Because sometimes you really want to do line1, except, maybe it's ok if an error happens...

like image 10
Daren Thomas Avatar answered Oct 15 '22 19:10

Daren Thomas


just put a try catch around line1

try
{
    try
    {
        line1
    }
    catch (Exception ex)
    {
       ...
    }

    line2
    ...
}
catch (Exception ex)
{
    ...
}

Frederik is right though you really need to be careful when doing this. It should be used on a case by case basis. Only when you know that the process should continue should you use it. Otherwise you should handle the exception accordingly.

like image 5
Josh Mein Avatar answered Oct 15 '22 18:10

Josh Mein