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

c# – 捕获异常,记录并再次抛出异常是一种好习惯吗?

发布时间:2020-12-15 08:34:49 所属栏目:百科 来源:网络整理
导读:出于记录的目的,我想捕获一个例外.但是因为我还需要抛出异常,然后我会再次抛出异常.例如,我会在C#中执行此操作,如下所示: try{ //exception-prone code block here}catch(Exception ex){ Logger.Log(ex); throw new Exception(ex);} 现在我很好奇这是记录目
出于记录的目的,我想捕获一个例外.但是因为我还需要抛出异常,然后我会再次抛出异常.例如,我会在C#中执行此操作,如下所示:
try
{
    //exception-prone code block here
}
catch(Exception ex)
{
   Logger.Log(ex);
   throw new Exception(ex);
}

现在我很好奇这是记录目的的最佳方式吗?建议请.

解决方法

没有最好的记录方式.它总是取决于你需要什么.

但是,如果您想减少代码并只记录错误,您可以创建自己的事件处理程序并将其附加到特定事件.

以AppDomain.UnhandledException事件为例:

来自MSDN的演示代码:

public class Example 
{
   [SecurityPermission(SecurityAction.Demand,Flags=SecurityPermissionFlag.ControlAppDomain)]
   public static void Main()
   {
      AppDomain currentDomain = AppDomain.CurrentDomain;
      currentDomain.UnhandledException += new UnhandledExceptionEventHandler(MyHandler);

      try {
         throw new Exception("1");
      } catch (Exception e) {
         Console.WriteLine("Catch clause caught : {0} n",e.Message);
      }

          throw new Exception("2");
       }

       static void MyHandler(object sender,UnhandledExceptionEventArgs args) 
       {
          Exception e = (Exception) args.ExceptionObject;
          Console.WriteLine("MyHandler caught : " + e.Message);
          Console.WriteLine("Runtime terminating: {0}",args.IsTerminating);
       }
    }
}

您可以将您的登录名放在MyHandler方法中并完成它.在没有真正处理异常的情况下,您不需要滥用catch块.

在Asp.Net中,您可以覆盖global.asax中的Application_Error方法:

protected void Application_Error()
{
    Exception ex = Server.GetLastError();
    NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
    logger.Fatal(ex);
}

根据您的日志记录例程,现在可以完成任何事情.在我的上述情况中,每个致命异常都会通过电子邮件发送到事件管理系统.

在我的观点中,关键点是,try / catch应该处理异常.在catch块中记录错误就像在catch块中有一个no语句一样,你只是吞下异常而不处理它.最后它只是冗余代码.

(编辑:李大同)

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

    推荐文章
      热点阅读