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);
}

相关文章

目录简介使用JS互操作使用ClipLazor库创建项目使用方法简单测...
目录简介快速入门安装 NuGet 包实体类User数据库类DbFactory...
本文实现一个简单的配置类,原理比较简单,适用于一些小型项...
C#中Description特性主要用于枚举和属性,方法比较简单,记录...
[TOC] # 原理简介 本文参考[C#/WPF/WinForm/程序实现软件开机...
目录简介获取 HTML 文档解析 HTML 文档测试补充:使用 CSS 选...