异常层次结构真的有用吗?

编程入门 行业动态 更新时间:2024-10-12 20:20:58
本文介绍了异常层次结构真的有用吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 对我来说,我从来没有看到一个异常层次结构,它创建子类,但是捕获父类实际上是有用的(除了当然,对于基本的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.

更多推荐

异常层次结构真的有用吗?

本文发布于:2023-11-07 00:19:26,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1565048.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:有用吗   层次   异常   结构

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!