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)?
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 ...
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...
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With