我定义了这样的自定义异常:
[Serializable]
public class WrongFileException : Exception
{
public WrongFileException()
{
}
public WrongFileException(string message) : base(message)
{
}
public WrongFileException(string message, Exception innerExeException) : base(message, innerExeException)
{
}
}
我有一个打开文件的按钮,我想在错误的文件时抛出异常:
private void PanelOpen_Click(object sender, RoutedEventArgs e)
{
Microsoft.Win32.OpenFileDialog opendlg = new Microsoft.Win32.OpenFileDialog();
opendlg.DefaultExt = ".xml";
opendlg.Filter="XML Files|*.xml";
Nullable<bool> result = opendlg.ShowDialog();
if (result == true)
{
XmlSerializer XMLSerial = new XmlSerializer(typeof(List<Panel>));
FileStream fsCheck = new FileStream(opendlg.FileName, FileMode.Open);
XmlReader reader = new XmlTextReader(fsCheck);
fsCheck.Close();
if (!XMLSerial.CanDeserialize(reader))
{
throw (new WrongFileException("Wrong data sructure for PanelList"));
}
try
{
using (FileStream fsRead = new FileStream(opendlg.FileName, FileMode.Open, FileAccess.Read))
{
PanelList = XMLSerial.Deserialize(fsRead) as List<Panel>;
}
PanelBoxListView.ItemsSource = PanelList;
PanelBoxListView.Items.Refresh();
}
catch(WrongFileException q)
{
MessageBox.Show("WrongFileException: {0}", q.Message);
throw;
}
}
CheckForListEntries();
}
测试它试图打开一个无效的文件我得到“WrongFileException未处理”。我不明白为什么因为我正在捕捉异常?
答案 0 :(得分:2)
只有在try块中抛出异常时才会捕获它。
try
{
if (!XMLSerial.CanDeserialize(reader))
{
throw (new WrongFileException("Wrong data sructure for PanelList"));
}
using (FileStream fsRead = new FileStream(opendlg.FileName, FileMode.Open, FileAccess.Read))
{
PanelList = XMLSerial.Deserialize(fsRead) as List<Panel>;
}
PanelBoxListView.ItemsSource = PanelList;
PanelBoxListView.Items.Refresh();
}
catch(WrongFileException q)
{
MessageBox.Show("WrongFileException: {0}", q.Message);
throw;
}
答案 1 :(得分:1)
<{em> <{1}}阻止你的throw (new WrongFileException(...));
,因此try
- try
永远不会变得相关。