2017-04-24 61 views
5

我試圖捕獲異步方法內引發的自定義異常,但由於某種原因它總是被泛型異常catch塊捕獲。見下面從異步方法中捕獲自定義異常

class Program 
{ 
    static void Main(string[] args) 
    { 
     try 
     { 
      var t = Task.Run(TestAsync); 
      t.Wait(); 
     } 
     catch(CustomException) 
     { 
      throw; 
     } 
     catch (Exception) 
     { 
      //handle exception here 
     } 
    } 

    static async Task TestAsync() 
    { 
     throw new CustomException("custom error message"); 
    } 
} 

class CustomException : Exception 
{ 
    public CustomException() 
    { 
    } 

    public CustomException(string message) : base(message) 
    { 
    } 

    public CustomException(string message, Exception innerException) : base(message, innerException) 
    { 
    } 

    protected CustomException(SerializationInfo info, StreamingContext context) : base(info, context) 
    { 
    } 
} 
+0

是因爲它抓住了AggregateException? – Stuart

+0

被捕獲的異常是什麼類型?它可能是一個'AggregateException',它可能包含你的'CustomException' –

回答

6

示例代碼的問題是,Wait拋出AggregateException,不是你想捕獲異常。

您可以使用此:

try 
{ 
    var t = Task.Run(TestAsync); 
    t.Wait(); 
} 
catch (AggregateException ex) when (ex.InnerException is CustomException) 
{ 
    throw; 
} 
catch (Exception) 
{ 
    //handle exception here 
} 
+0

這解決了它。感謝您的解釋。 – sloppy