c# – 尝试抓住投掷

我试图理解我将如何在我的代码中使用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);
}

相关文章

原文地址:http://msdn.microsoft.com/en-us/magazine/cc163...
前言 随着近些年微服务的流行,有越来越多的开发者和团队所采...
最近因为比较忙,好久没有写博客了,这篇主要给大家分享一下...
在多核CPU在今天和不久的将来,计算机将拥有更多的内核,Mic...
c语言输入成绩怎么判断等级
字符型数据在内存中的存储形式是什么