[英]C# user defined exception not being caught
I defined my custom exception like this:我像这样定义了我的自定义异常:
[Serializable]
public class WrongFileException : Exception
{
public WrongFileException()
{
}
public WrongFileException(string message) : base(message)
{
}
public WrongFileException(string message, Exception innerExeException) : base(message, innerExeException)
{
}
}
I have a button that opens a file and I want to throw an exception when it's the wrong file:我有一个打开文件的按钮,当它是错误的文件时,我想抛出异常:
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();
}
Testing it trying to open with a file that won't work I get "WrongFileException was unhandled".测试它试图用一个不起作用的文件打开我得到“WrongFileException 未处理”。 I don't get why because I am catching the exception?
我不明白为什么,因为我正在捕获异常?
Your throw (new WrongFileException(...));
你的
throw (new WrongFileException(...));
is before the try
block, so the try
- catch
never becomes relevant.在
try
块之前,所以try
- catch
永远不会变得相关。
It catches only if the exception is thrown within try block.只有在 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; throw only if you handle/log it down the track
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.