2017-04-24 15 views
5

Bir async yöntemine atılan özel bir özel durum yakalamaya çalışıyorum ancak bazı nedenlerden dolayı her zaman genel istisna tutma bloğu tarafından yakalanıyor. Sorun Wait bir AggregateException, sen değil yakalamaya çalışıyoruz istisna atar olmasıdırEşzamanlı olmayan bir yöntemden özel istisnaları yakala

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

mi: Bu kullanabilirsiniz

? – Stuart

+0

Yakalanan istisna türü nedir? Bu, 'CustomException' –

cevap

6

aşağıdaki örnek kodu bakın. o AggregateException alıcı çünkü o

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

'unuzu içerebilecek bir "AggregateException" olabilir. Bunu çözdünüz. Açıkladığın için teşekkürler. – sloppy

İlgili konular