C#不会抓住"嵌套"自定义例外

时间:2017-12-02 19:05:17

标签: c# try-catch

我试图抓住"嵌套"或"封装"我的代码中的自定义错误(I504Error)。我知道这通常不是最佳实践,但它应该适用于我的用例,因为错误是非常具体的。我试图让try/catch阻止在我的I504Error方法中捕获Main,但它并没有抓住它,即使它被调用了从try/catch块内部。我的程序停在我抛出错误的地方。我在这里做错了什么?

// Custom Error Handler
public class I504Error : Exception
{
    public I504Error()
    {
    }
}

// Classes

public abstract class AbstractIternetThing
{
    public abstract void DoSomething();
}

public class IternetThing : AbstractIternetThing
{
    public override void DoSomething()
    {
        // bunch of other stuff
        if (iternetThingWorkedProperly == false)
        {
            // Program stops here, doesn't get caught by the try/catch block in Program.Main()
            throw new I504Error();
        }
    }
}

// Main script
class Pogram
{
    static void Main(string[] args)
    {
        List<Task<AbstractIternetThing>> programThreads = new List<Task<AbstractIternetThing>>();
        IternetThing iThing = new IternetThing();

        try
        {
            for (int wantedThread = 0; wantedThread < 5; wantedThread++)
            {
                Task<AbstractIternetThing> iThingTask = new Task<AbstractIternetThing>(() => iThing.DoSomething());
                iThingTask.Start();
            }
        }
        // The Error should get caught here, but it doesnt?
        catch (I504Error)
        {
            // Do something else
        }
    }
}

1 个答案:

答案 0 :(得分:2)

这是因为你在Task中拥有它,它位于一个单独的异步执行路径上。考虑使用async-await。然后编译器将重写您的代码,使其按预期工作。