禁用在异常时中断代码执行

时间:2015-03-20 14:30:18

标签: c#

如果我写这样的话:

void Code()
{
   Console.WriteLine("a");
   throw new Exception(); //the code will stop executing here
   Console.WriteLine("b");
}

代码将在写完" a"之后停止执行控制台。我想知道,是否可以执行整个函数然后抛出异常?因此,如果在Console.WriteLine(" a")之间抛出异常;和Console.WriteLine(" b");它将停止代码执行,但我希望在抛出异常之前完全执行该函数

3 个答案:

答案 0 :(得分:2)

根本没有真正的建议,但我想你可以做这样的事情。

var errors = new List < Exception > ();
Console.WriteLine("a");
try {
    ErrorThrowingMethod();
} catch (Exception e) {
    errors.Add(e);
}
Console.WriteLine("b");
if (errors.Any()) throw new AggregateException(errors);

答案 1 :(得分:1)

简单地说:不,你不能。 并且不应该尝试将编程逻辑弯曲成这种方式。 一个例外是指示某些内容非常错误且函数必须在没有返回值的情况下退出。这是异常的目的,表示运行该函数时出错,并且可能无法完成执行。

void Code()
{
   Boolean anyErrors = false;
   Console.WriteLine("a");
   anyErrors = true; // whenever something goes wrong.
   Console.WriteLine("b");
   if(anyErrors)
       throw new Exception("There were errors doing whatever I was trying to.");
}

在这种情况下你也可以:

// will return false if it fails and true if succeeds.
Boolean Code()
{
   Boolean anyErrors = false;
   Console.WriteLine("a");
   anyErrors = true; // whenever something goes wrong.
   Console.WriteLine("b");
   return !anyErrors;
}

逻辑是编程的基础,思考逻辑,你不必与语言作斗争。

答案 2 :(得分:0)

你可以做到

void Code()
{
    try
    {
        Console.WriteLine("a");
        throw new Exception(); //the code will stop executing here
        Console.WriteLine("b");
    }
    catch(Exception e)
    {
        Console.WriteLine("b");
        throw new Exception(e.toString());
    }
}

这将完成我认为你在这个特定情况下试图实现的目标,但正如所提到的,由于事先依赖事件,尝试继续是没有意义的。