加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 尝试抓住投掷

发布时间:2020-12-15 04:34:03 所属栏目:百科 来源:网络整理
导读:我试图理解我将如何在我的代码中使用Throw.我有一个MainForm类来处理 Windows窗体GUI,然后我有Manager类来读取和保存文件中的数据. 我在两个课程中都使用了Try / Catch,但我的导师希望我在Manager课程中使用Throw,尽管我正在阅读它,但我不明白它会做什么? W
我试图理解我将如何在我的代码中使用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);
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读