【发布时间】: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