异常层次结构真的有用吗? [英] Are exception hierarchies really useful?

查看:129
本文介绍了异常层次结构真的有用吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对我来说,我从来没有看到一个异常层次结构,它创建子类,但是捕获父类实际上是有用的(除了当然,对于基本的Exception类,具有被导出)



异常层次结构真的很有用,xor是否应该从语言的基类异常类派生异常?

解决方案

当您在不同的地方需要不同粒度的捕捉时,异常层次结构对于将相关异常组合在一起很有用。



所有应用程序异常在一个地方是最常见的用例。这允许您随时捕获 MyAppException ,以避免您的应用程序发生错误,但是在适当的时候仍然可以捕获更多特定的异常。 (在.NET中, ApplicationException 类是为此而已,但由于各种原因已被弃用。)



但是,您也可以在模块边界处以任何其他方式将异常组合在一起。对于来自 Foo 模块的异常,使用 FooModuleException ,但捕获并处理 FooModuleMustFrobnicate 特别内部 Foo 。或任何等同的情况。



我在不同的时间使用了所有这些模式。


It dawned on me that I've never seen a single exception hierarchy for which creating subclasses but catching the parent class was actually useful (except, of course, for the base Exception class, that has to be derived).

Are exception hierarchies really useful, xor should all exceptions be derived from language's base exception class?

解决方案

Exception hierarchies are useful for grouping related exceptions together, when you need different granularity of catching in different places.

Putting all application exceptions in one place is the commonest use case. This allows you to catch MyAppException any time that you want to trap all errors coming from your application, but still catch more specific exceptions when appropriate. (In .NET, the ApplicationException class was meant for this, but it's been deprecated for various reasons.)

But you can also group exceptions together at module boundaries, or in any other way that makes sense. Use FooModuleException for exceptions coming from the Foo module, but catch and handle FooModuleMustFrobnicate specially internal to Foo. Or any equivalent situation.

I've used all of these patterns at different times.

这篇关于异常层次结构真的有用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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