2017-04-24 16 views
5

से कस्टम अपवादों को पकड़ें मैं एक एसिंक विधि के अंदर फेंक दिया गया एक कस्टम अपवाद पकड़ने की कोशिश कर रहा हूं लेकिन किसी कारण से यह हमेशा सामान्य अपवाद पकड़ ब्लॉक द्वारा पकड़ा जा रहा है। नीचेएसिंक विधि

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

अपवाद पकड़ा जा रहा है किस प्रकार का? यह एक 'समेकित अपवाद' हो सकता है जिसमें आपका 'कस्टम अपवाद' –

उत्तर

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

संबंधित मुद्दे