如何处理例外 [英] How to deal with exceptions

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

问题描述

我的技术主管坚持这种异常机制:

My technical lead insists on this exception mechanism:

try
{
    DoSth();
}
catch (OurException)
{
    throw;
}
catch (Exception ex)
{
    Util.Log(ex.Message, "1242"); // 1242 is unique to this catch block
    throw new OurException(ex);
}

1242这里是一个catch方法的标识符,我们处理除了OurException。项目中的每个catch块都必须有一个唯一的标识符,所以我们可以通过查看日志知道异常发生的位置。

1242 here is an identifier of the catch method which we handle an exception other than OurException. Every catch block in the project must have a unique identifier so we can know where the exception occurred by looking at the logs.

对于每个方法,我们必须捕获OurException和丢它。如果抛出其他类型的异常,我们必须在重新抛出之前将其记录并通过OurException进行掩码。

For every method, we have to catch OurException and throw it. If an other type of exception is thrown, we have to log it and mask it by OurException before rethrowing it.

这是否合理?如果有的话,有什么更好的选择?

Is this a reasonable approach? If there are any, what are the better alternatives?

编辑:我被告知堆栈跟踪在发布中没有产生有意义的结果模式。
你建议捕捉和抛出泛型异常吗?

I've been told the stack trace does not produce meaningful results in release mode. Are you suggesting catching and throwing generic exceptions is OK?

Edit2:谢谢大家。我使用你的答案作为我反对的论据的一部分,但我被告知你没有足够的经验,不知道如何处理现实生活中的情况。我必须这样做。

Thank you all. I used your answers as part of my argument against this but I've been told you are not experienced enough and do not know how to deal with real life situations. I have to go this way.

推荐答案

您还可以查看异常处理应用程序块

我已经在很少的项目,这是非常有用的。特别是如果你想稍后更改异常处理的工作原理以及要捕获的信息。

I have used it in a few projects and it is very useful. Especially if you want to later change how your exception handling works, and what information to capture.

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

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