2017-12-02 103 views
0

我試圖在代碼中捕捉到「嵌套」或「封裝」自定義錯誤(I504Error)。我知道這通常不是最佳實踐,但它應該適用於我的用例,因爲錯誤非常具體。我試圖讓try/catch區塊在我的Main方法中捕獲I504Error,但它無法捕獲它,即使它是從try/catch區塊內部調用的。我的程序停止在我拋出錯誤的地方。我在這裏做錯了什麼?C#不會捕獲「嵌套」自定義異常

// 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 
     } 
    } 
} 

回答

2

這是因爲你有它在一個Task這是在一個單獨的異步執行路徑。考慮使用異步等待。然後編譯器會重寫您的代碼,使其按照您的預期工作。