我正在尝试了解如何在我的代码中使用 Throw。我有一个 MainForm 类来处理 Windows 窗体 GUI,然后我有一个 Manager 类来从文件读取数据/向文件保存数据。
我在两个类(class)中都使用了 Try/Catch,但我的导师希望我在 Manager 类(class)中使用 Throw,尽管我正在阅读它,但我不明白它会做什么? Throw会影响MainForm类中的Try/Catch吗?
如果捕获到异常,我也会在管理器类中使用消息框,但根据讲师的说法,管理器中不允许使用消息框,那我该怎么办?我可以只在 MainForm 类中使用消息框吗? Preciate一些有助于理解和扩展我的知识!谢谢!
主窗体类:
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();
}
最佳答案
你的经理类应该是这样的:
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!", "Varning!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
关于c# - try catch ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11718693/