c# – 尝试抓住投掷

c# – 尝试抓住投掷,第1张

概述我试图理解我将如何在我的代码中使用Throw.我有一个MainForm类来处理 Windows窗体GUI,然后我有Manager类来读取和保存文件中的数据. 我在两个课程中都使用了Try / Catch,但我的导师希望我在Manager课程中使用Throw,尽管我正在阅读它,但我不明白它会做什么? Will Throw会影响MainForm类中的Try / Catch吗? 如果捕获到异常,我也会在 我试图理解我将如何在我的代码中使用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);}
总结

以上是内存溢出为你收集整理的c# – 尝试抓住投掷全部内容,希望文章能够帮你解决c# – 尝试抓住投掷所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1263795.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-08
下一篇 2022-06-08

发表评论

登录后才能评论

评论列表(0条)

保存