开发者

How to resume computation on exception in C#?

try
{
    statement 1;
    statement 2;
    statement 3;
    statement 4;
    statement 5;
}
catch
{
}

The above is the typical try-catch. If one of the statment goes into catch, the coding will jump the rest statement.

What I want to do is..

let's say, statement 2 has an error and goes开发者_StackOverflow中文版 into exception, I still want to work on statement 3,4, and 5.

I m just curious how can I achieve that?

The simplest answer would be 5 try-catch.

But I think it is too childish.


Using separate try .. catch constructs would be the best thing to do in general, because you should handle the most specific exceptions (which can be different for different statements). Also, an exception can create an invalid state, so continuing may not be the best thing to do.

If you're just looking for a simpler syntax to write it and you need to repeat the same exception handling, you can use lambdas and write something like:

CallWithCatch
 ( () => statement1,
   () => statement2,
   () => statement3,
   /* ... */ );

Where the definition of CallWithCatch looks like this:

void CallWithCatch(params Action[] statements) {
  foreach(var statement in statements) { 
    try { 
      statement();
    } catch(/* your exception */) {
      // your exception handler
    }
  }
}


So generally speaking, all of your statements probably throw exceptions, and you want to continue to execute following statements if one throws exception. The simplest solution is:

try
{
   statement1;
}
catch {}
try
{
   statement2;
}
catch {};
...

which looks bad. An improvement is:

public void TryStatements(params Action[] actions)
{
   foreach(Action act in actions)
   {
     try
     {
        act();
     }
     catch(SomeCommonException ex)
     {
        //do something special
     }
     catch(Exception ex)
     {
        //something else
     }
   }
}

then you can:

   TryStatement(()=>statement1,()=>satement2);


You need to catch each exception individually.

try 
{     
    statement 1;     
}
catch {}

try
{
    statement 2;
}
catch {} 

// etc

Alternatively you can extract statement1, statement2 etc into their own methods, each of which contains their own try/catch. This way each of those operations can concern themselves with any particular exceptions, and you can handle all the expected exceptions, letting unhandled exceptions bubble up as normal.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜