抛出一个新的异常最佳实践 [英] Throwing a New Exception Best Practice

查看:153
本文介绍了抛出一个新的异常最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是好的做法,如果没有应该做什么?

 赶上(例外五)
{
     抛出新的异常(e.Message,E);
}
 

解决方案

没有,这不是很好的做法,如果你抛出另一个异常的类型完全相同的同一消息的。在这一过程中,你复杂的堆栈跟踪,使调试更加的痛苦。

如果你要抛出一个新的异常,它应该以某种方式显著不同于原来的。它应该是另一种类型,例如,或者以其他方式(如更具体的错误消息)澄清的异常的原因。如果你不能做这些事情,然后用简单的重新抛出当前异常扔;

,或者甚至更好,不抓住它。实际上重新抛出弄乱堆栈跟踪一点点,以及(当前帧的错误位置设置为重新抛出点,而不是那里的例外发生的部位),所以如果你没有什么,你个人必须做的处理异常,然后把手拿开 - 只是让它传播,让来电处理它

Is the following good practice and if not what should be done?

catch(Exception e)
{
     throw new Exception(e.Message, e);
}

解决方案

No, this is not good practice if you're throwing another exception of the exact same type with the same message. In doing this, you complicate the stack trace and make debugging more of a pain.

If you're going to throw a new exception, it should differ from the original in some significant way. It should be another type, for example, or in some other way (like a more specific error message) clarify the reason for the exception. If you can't do either of those things, then simply rethrow the current exception using throw;.

Or, even better, don't catch it at all. Rethrowing actually messes up the stack trace a tiny bit as well (the current frame's error location is set to the rethrow point rather than the spot where the exception happened), so if you don't have anything you personally have to do to handle the exception, then hands off -- just let it propagate and let the caller handle it.

这篇关于抛出一个新的异常最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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