【问题标题】:C# won't catch "nested" custom exception [duplicate]C# 不会捕获“嵌套”自定义异常 [重复]
【发布时间】:2018-05-16 15:02:10
【问题描述】:

我试图在我的代码中捕获“嵌套”或“封装”自定义错误 (I504Error)。我知道这通常不是最佳实践,但它应该适用于我的用例,因为错误非常具体。我试图让try/catch 块在我的Main 方法中捕获I504Error,但它没有捕获它,即使它是从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
        }
    }
}

【问题讨论】:

    标签: c# try-catch


    【解决方案1】:

    这是因为您将它放在一个单独的异步执行路径上的Task 中。考虑使用异步等待。然后编译器会重写你的代码,让它按照你的预期工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-31
      • 1970-01-01
      • 2011-09-22
      • 2018-01-25
      • 2017-05-24
      • 2020-04-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多