c# - try catch

标签 c# .net

我正在尝试了解如何在我的代码中使用 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/

相关文章:

c# - IEnumerable 集合声明和填充

c# - 如何使用 EF 代码优先 POCO 创建 View

c# - 从 xml REST POST webResponse 解析 C# 中的 XML

c# - 使用 DX11 渲染文本

c# - 自定义控件上的 AutomationProperties.AutomationId 未公开

c# - 使用 JsonConvert C# 解析 json 字符串

.net - 如何让一个用户组件成为WinForms中数据绑定(bind)的数据源?

c# - 每次 SQL Server 表更改时,如何让 Windows 窗体客户端更新?

c# - 如果未返回,则在间隔后终止线程

c# - 检测违反了多个唯一键中的哪个?