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

前端之家收集整理的这篇文章主要介绍了c# – 捕获异常,记录并再次抛出异常是一种好习惯吗?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
@H_301_1@出于记录的目的,我想捕获一个例外.但是因为我还需要抛出异常,然后我会再次抛出异常.例如,我会在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语句一样,你只是吞下异常而不处理它.最后它只是冗余代码.

原文链接:https://www.f2er.com/csharp/244090.html

猜你在找的C#相关文章