我试图理解我将如何在我的代码中使用Throw.我有一个MainForm类来处理
Windows窗体GUI,然后我有Manager类来读取和保存文件中的数据.
我在两个课程中都使用了Try / Catch,但我的导师希望我在Manager课程中使用Throw,尽管我正在阅读它,但我不明白它会做什么? Will Throw会影响MainForm类中的Try / Catch吗?
如果捕获到异常,我也会在manager类中使用一个消息框,但是根据教师的说法,不允许在管理器中使用消息框,那么我该怎么办呢?我可以只在MainForm类中使用消息框吗?帮助理解和扩展我的知识!谢谢!
MainForm类:
try { motelManager.SaveToFile(file); } catch { MessageBox.Show("Ett fel uppstod!","Varning!",MessageBoxButtons.OK,MessageBoxIcon.Exclamation); }
经理班:
public void SaveToFile(string filePath) { try { string newFilePath = filePath.Replace(".bin",""); filestream = new FileStream(newFilePath + ".bin",FileMode.Create); BinaryFormatter b = new BinaryFormatter(); b.Serialize(filestream,animals); } catch(Exception ex) { MessageBox.Show(ex.Message,MessageBoxIcon.Exclamation); } if (filestream != null) filestream.Close(); }
解决方法
您的经理类应该如下所示:
public void SaveToFile(string filePath) { try { string newFilePath = filePath.Replace(".bin",""); filestream = new FileStream(newFilePath + ".bin",FileMode.Create); BinaryFormatter b = new BinaryFormatter(); b.Serialize(filestream,animals); } catch(Exception ex) { if (filestream != null) filestream.Close(); throw; // but don't use // throw ex; // it throws everything same // except for the stacktrace } // or do it like this //catch(Exception ex) //{ // throw; // but don't use // throw ex; // it throws everything same // except for the stacktrace //} //finally //{ // if (filestream != null) filestream.Close(); //} }
在你的主要班级:
try { motelManager.SaveToFile(file); } catch (Exception e) { MessageBox.Show("Ett fel uppstod!",MessageBoxIcon.Exclamation); }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。