在C#中将控制流结构添加到异常管理器?

时间:2017-07-11 18:03:53

标签: c# .net try-catch

如何将控制流(if-else结构)用于try-catch,我的意思是,如何使程序尝试任务A ,如果它抛出异常则转到任务B 。一种方法是像这样嵌套的try-catch

  try{ 
    ....
    } catch(exception ex1)
    try{ 
    ....
    } catch(exception ex2) {
        try{
           }
     ....

但是这个结构是不可扩展的,如果需要检查100个情况,我们应该编写100个嵌套的try-catches吗?

5 个答案:

答案 0 :(得分:2)

如果你愿意,你可以自由地嵌套尝试/捕获多个级别。

try 
{
   operation1();
}
catch (Exception e)
{
   try
   {
     operation2();
   }
   catch (Exception e2)
   {
      // etc
   }
}

答案 1 :(得分:1)

只需在catch-block中编写另一个try-block。

try {
  //task A
} catch(Exception ex) {
  try {
    //task B
  }
}

答案 2 :(得分:1)

另一个选择是将您的任务移动到返回bool表示成功的方法,然后您不必嵌套您的try / catches:

public static bool TrySomething(string someInput)
{
    bool result = true;

    try
    {
        // do something with someInput
    }
    catch
    {
        result = false;
    }

    return result;
}

public static bool TrySomethingElse(string someInput)
{
    bool result = true;

    try
    {
        // do something with someInput
    }
    catch
    {
        result = false;
    }

    return result;
}

然后在主代码中,你可以这样做:

string data = "some data";

if (!TrySomething(data))
{
    TrySomethingElse(data);
}

答案 3 :(得分:1)

鉴于您需要这100次并且必须对您的控制流使用异常(如果可能应该避免)。您可以使用一些包装器,如下所示:

public class ExWrapper
{
    private readonly Action _action;
    private readonly ExWrapper _prev;

    private ExWrapper(Action action, ExWrapper prev = null)
    {
        _action = action;
        _prev = prev;
    }

    public static ExWrapper First(Action test)
    {
        return new ExWrapper(test);
    }

    public ExWrapper Then(Action test)
    {
        return new ExWrapper(test, this);
    }

    public void Execute()
    {
        if (_prev != null)
            try
            {
                _prev.Execute();
            }
            catch (Exception)
            {
                _action();
            }
        else
            _action();
    }
}

这允许您链接动作,只有在第一个动作抛出时才执行下一个动作。您可以使用它,如以下示例所示:

ExWrapper.First(() => { Console.WriteLine("First");   throw new Exception(); })
         .Then( () => { Console.WriteLine("Second");  throw new Exception(); })
         .Then( () => { Console.WriteLine("Third");   throw new Exception(); })
         .Then( () => { Console.WriteLine("Fourth"); })
         .Execute();

这将按给定的顺序执行所有操作或lambdas,但只有在第一次抛出时才会执行以下操作。上面的例子打印:

First
Second
Third
Fourth

如果您删除示例中的throws

ExWrapper.First(() => { Console.WriteLine("First");  })
         .Then( () => { Console.WriteLine("Second"); })
         .Then( () => { Console.WriteLine("Third");  })
         .Then( () => { Console.WriteLine("Fourth"); })
         .Execute();

仅执行第一个操作,从而产生以下输出:

First

答案 4 :(得分:0)

嵌套的try-catch使用大量资源,如果它们失控,它们会显着降低程序的性能。但是,您可以按顺序添加catch块:

try  
{
    //code here
}catch(SomeException ex)
{
    //Display what the specific exception was
}catch(SomeOtherException ex)
{
    //Display what the specific exception was
}