异常和抽象 [英] Exceptions and Abstractions

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

问题描述

什么时候应该抛出自定义异常?

When should you throw a custom exception?

例如我有一些连接到服务器的代码.连接到服务器的代码在连接失败时抛出 IOException.在它被调用的方法的上下文中,这很好.在网络代码中也很好.

e.g. I have some code that connects to a server. The code that connects to the server throws an IOException when it fails to connect. In the context of the method it's called, this is fine. It's also fine in the network code.

但由于这表示没有连接(因此无法正常工作),因此异常一直持续到 ui.在这个阶段,IOException 是非常模糊的.像 NoConnectionException 这样的东西会更好.

But as this represents not having a connection (and therefore not working) the exception goes all the way up to the ui. At this stage, an IOException is very ambigous. Something like NoConnectionException would be better.

所以,我的问题是:您应该在哪个阶段捕获异常,而不是抛出另一个更适合抽象的(自定义)异常?

So, my question is: At what stage should you catch an exception to instead throw another (custom) exception that better fits the abstraction?

推荐答案

我希望异常能够根据我要求原始方法执行的操作进行讨论.例如

I would expect exceptions to talk in terms of what I've asked the originating method to do. e.g.

read -> ReadException
connect -> ConnectException
buildPortfolio -> FailedToBuildPortfolioException

等等.这抽象了幕后发生的事情(即您是否通过套接字等连接).作为一般规则,当我为一个组件创建一个接口时,我经常创建一个相应的异常或一组异常.我的接口将被称为 Component,我的异常通常是 ComponentException(例如 RateSourceRateSourceException).作为一个完整的组件集导出到不同的项目是一致且容易的.

etc. This abstracts away what's going on under the covers (i.e. are you connecting via sockets etc.). As a general rule, when I create an interface for a component, I often create a corresponding exception or set of exceptions. My interface will be called Component, and my exceptions are usually ComponentException (e.g. RateSource and RateSourceException). It's consistent and easy to export to different projects as a complete component set.

缺点是您创建了相当多的异常,并且您可能需要执行相当多的翻译.好处是(正如您所确定的)您几乎没有抽象泄漏.

The downside is that you create quite a lot of exceptions, and you may have to perform quite a lot of translations. The upside is that (as you've identified) you get little to no abstraction leakage.

在方法调用(以及异常)的层次结构中的某个时刻,您可能会决定无法进行恢复(或在不适当的位置),并转换为未经检查的异常以供稍后处理.

At some point during the hierarchy of method calls (and thus exceptions) you may decide that no recovery can take place (or it's at an inappropriate place) and translate to unchecked exceptions to be handled later.

这篇关于异常和抽象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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