【发布时间】:2012-07-30 09:29:26
【问题描述】:
我正在尝试了解如何在我的代码中使用 Throw。我有一个 MainForm 类来处理 Windows 窗体 GUI,然后我有一个 Manager 类来读取和保存文件中的数据。
我在两个课程中都使用 Try/Catch,但我的导师希望我在 Manager 课程中使用 Throw,尽管我正在阅读它,但我不明白它会做什么? Throw 会影响 MainForm 类中的 Try/Catch 吗?
如果捕获到异常,我也会在管理器类中使用消息框,但是根据讲师的说法,管理器中不允许出现消息框,那我该怎么办?我可以只在 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, "Varning!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
if (filestream != null) filestream.Close();
}
【问题讨论】:
-
这段代码让我担心,它看起来像一个文件路径被传入并且一个流被打开到一个全局变量,那么如果有一个问题你要调用关闭,如果你关闭了你的filestream 如果不重新分配,您将无法重新打开它,在这种情况下,此代码不好,因为它总是会关闭它。您应该在此处使用“使用”块在调用 close 后调用 dispose。