如何实现顶级异常处理? [英] How to implement top level exception handling?

查看:127
本文介绍了如何实现顶级异常处理?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近不得不为同事开发的现有服务开发一个额外的模块。他在主要工作功能中放置了一个try / catch块,用于捕获所有冒泡的异常,并将其与堆栈跟踪信息一起记录在一起。

  try 
{
//主要工作
}
catch(Exception ex)
{
//日志异常info
}

虽然这样使程序非常稳定(如不太可能崩溃 ),我讨厌它,因为当我测试我的代码时,我没有看到它引起的异常。当然,我可以看一下例外日志,看看是否有新的条目,但是我非常喜欢直接反馈获取异常的时刻(请注意代码中右边的光标)。 / p>

我在编译和测试时至少删除了这个顶级的try / catch。但是现在我的任务已经完成了,我必须决定把它放回去发布。
我认为我应该这样做,因为它使服务更加稳定,而且它的全部要点是它在后台运行而不需要任何监督。另一方面,我已经看过,只应该调用特定的异常(如 IoException ),而不是一般地异常



您对这个问题的建议是什么?



顺便说一句,项目是用C#编写的,但是我也对非.NET语言的答案感兴趣。

解决方案

把它放回来。



测试时该例外应该是相关的。否则,毫无意义的弹出它给用户。



日志记录正常。



您可以另外使用Visual Studio定义的DEBUG符号作为标记调试版本。

  ... 
} catch(Exception e){
#if DEBUG
throw;
#else
日志一样
#endif
}

所以下次需要进行修改时,调试标志应设置为true,异常会弹出。


I recently had to develop an additional module for an existing service developed by a colleague. He had placed a try/catch block in the main working function for catching all unhadled exceptions that bubbled up to this level, logging them together with stack trace info etc:

try
{
    // do main work
}
catch(Exception ex)
{
    // log exception info
}

While this makes the program very stable (as in 'unlikely to crash'), I hate it because when I am testing my code, I do not see the exceptions caused by it. Of course I can look at the exception log and see if there are new entries, but I very much prefer the direct feedback of getting the exception the moment it is thrown (with the cursor on the right line in the code, please).

I removed this top level try/catch at least while i was still coding and testing. But now my task is finished and I have to decide wether to put it back in for the release, or not. I think that I should do it, because it makes the service more stable, and the whole point of it is that it runs in the background without needing any supervision. On the other hand I have read that one should only call specific exceptions (as in IoException), not generically Exception.

What is your advice on this issue?

By the way, the project is written in C#, but I am also interested in answers for non .NET languages.

解决方案

Put it back.

The exception should be only relevant while testing. Otherwise it doesn't make sense pop it to the user.

Logging is fine.

You may additionally use the DEBUG symbol defined by Visual Studio for debug builds as a flag.

    ...
    } catch( Exception e ) { 
#if DEBUG
          throw;
#else
          log as usual 
#endif
    }

So next time a modification is needed the debug flag should be set to true and the exception will pop up.

这篇关于如何实现顶级异常处理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆