【问题标题】:Handling unhandled exceptions处理未处理的异常
【发布时间】:2011-11-19 11:43:18
【问题描述】:

我有一个动态加载图像的应用程序。假设该图像不存在,我们想通知用户然后退出。在我的主循环中,我有异常处理,当我使用 StreamReader 读取文件时它工作得很好。但是,如果我从另一个函数抛出异常,应用程序就会崩溃,并且在错误报告中我会看到抛出的异常 (IOException)。要了解应用程序:

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_Click(object sender, RoutedEventArgs e)
    {
            ...
            if (!File.Exists(myFile)) {
                throw new IOException("File doesnt exist");
            }
            ...
    }

但是,如果我将 try-catch 块放在 Grid_Click 中,它会捕获该异常。

【问题讨论】:

  • “处理未处理的异常” - 那将是矛盾的。

标签: c# wpf exception-handling


【解决方案1】:

Grid-Click 中抛出的异常不会被 MainWindow() 方法中的 catch 语句捕获,因为对 Grid_Click 的方法调用不在 try 块内。

Grid_Click 方法在点击事件触发时被调用,这是在异步时间。只有 IOExceptions 在 MainWindow 中的 try 块内抛出的 IOExceptions 会被上面列出的 catch 语句捕获。

【讨论】:

    【解决方案2】:

    你所说的“主循环”只是一个构造函数。代码不在其控制下执行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-26
      相关资源
      最近更新 更多