Try/Catch doesn't catch exception c#

时间:2016-08-31 18:09:10

标签: c# wpf exception

I've try catch exception in this code:

    public Source(String source) /// Constructor
    {
        _dialogs = new ThreadSafeList<Int64>();
        _source = source;
        try
        {
            var request = WebRequest.Create(_source);
            var stream = request.GetResponse().GetResponseStream();
            XmlDocument doc = new XmlDocument();
            doc.Load(stream);

            _oldNews = doc.SelectNodes("/rss/channel/item").Cast<XmlNode>();
            IsValid = true;
        }
        catch (Exception e)
        {
            Logger.Log("Source read error " + source + ", more: " + e.Message);
            IsValid = false;
        }
    }

XmlException occurs in try block in doc.Load(stream) but doesn't catch. I find out that exist some exception types that can't be caught in the regular way. XmlException isn't such type of exception. Anyway I tried use [HandleProcessCorruptedStateExceptions] attribute and that won't help. How can i catch this exception? Stack Trace. I'll appriciate any suggestions

1 个答案:

答案 0 :(得分:0)

All the exception in the C# are derived from System.Exception. So, it is not possible for XmlException to be not caught using your code for try and catch.

Assumptions: a) The exception that you are trying to catch is occurring somewhere else like duplicated code in other module.

b) In case you want to catch XMLException explicitly the below code will help.

public static void Source(String source) /// Constructor
{
    try
    {
        var request = WebRequest.Create(source);
        var stream = request.GetResponse().GetResponseStream();         
        XmlDocument doc = new XmlDocument();
        doc.Load(stream);
    }
    catch(XmlException e) 
    {
       Console.WriteLine("XmlException Caught");
       Console.WriteLine(e.Message);
       Console.WriteLine("Exception object Line, pos: (" + e.LineNumber + "," + e.LinePosition  + ")");
    }       
    catch (Exception ex)
    {
        Console.WriteLine("Exception Caught");
        Console.WriteLine(ex.Message);
    }
}