开发者

Handling unhandled exceptions

I have an application where I load an image dynamically. Let's say, that image doesn't exists and we want to notify the user and then exit. In my main loop, I have exception handling which works just fine when I'm reading files with StreamReader. However, if I am throwing exception from another function, the app just crashes and in the error report I see thrown exception (IOException). To get an idea of the app:

public MainWindow()
{
    try {
        InitializeComponent();
        Load(myFile);
    } catch (IOException e) {
        MessageBox.Show("Opening failure.");
        Application.Current.Shutdown();
    } 
}

public void Load(string imgPath)
{
    string tmpStr;
    string[] tmp;
    using (StreamReader sr = new StreamReader("myFile.txt", System.Text.Encoding.Default)) {
        while ((tmpStr = sr.ReadLine()) != null) {
            tmp = tmpStr.Split(' ');

            ...
        }
    }
}

    private void Grid_Cli开发者_开发百科ck(object sender, RoutedEventArgs e)
    {
            ...
            if (!File.Exists(myFile)) {
                throw new IOException("File doesnt exist");
            }
            ...
    }

BUT, if I put try-catch block inside Grid_Click, it catches that exception.


The exception that is thrown in Grid-Click would not be caught by the catch statement in the MainWindow() method by design, since the method call to Grid_Click is not inside that try block.

The Grid_Click method is called when the click event is fired, which is at an asynchronous time. Only IOExceptions thrown inside the try block in MainWindow will be caught by that catch statement you have listed above.


What you call 'main loop' is just a constructor. The code does not execute under it's control.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜