什么时候提出例外? [英] When to raise an exception?

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

问题描述

我认为这是一个最佳实践类别的问题:

I think this is a "best practice" category question:

我有一个自定义控件-一种包含一些面板的网格。面板之一是当前活动面板(最后一个单击)。

I have a custom control - some kind of grid that holds some panels. One of the panels is the current active panel (the last one clicked).

TMyGrid = class (TSomeKindOfGrid)
  published
    property CurrentPanel: TPanel read getCurPanel write setCurPanel;
end;

我的问题是:是否在某个时候有人要求 CurrentPanel 并且网格为空, getCurPanel 应该返回NIL还是引发异常?

My question is: if at a certain point someone asks for the CurrentPanel and the grid is empty, should getCurPanel return a NIL or should it raise an exception?


  • 如果 getCurPanel 返回NIL,则我必须在各处/每次调用 CurrentPanel 。呼叫者也有可能忘记检查NIL。好吧,因为它将尝试访问NIL对象,所以不会发生任何坏事件。该程序将很好地崩溃在那里。而且我得到了堆栈跟踪。

  • 如果我在 getCurPanel 中引发异常,我只会在一个地方进行检查(是的,我很懒)。

  • If getCurPanel returns NIL, then I MUST check for NIL everywhere/every-time I call CurrentPanel. There is also a possibility that the caller forgets to check for NIL. Well, nothing "bad" will happen since it will try to access a NIL object. The program will nicely crash right there. And I get to get a stack trace.
  • If I raise an exception in getCurPanel, I only do the check in one place (yes, I'm lazy).

推荐答案

如果返回 nil ,您可以让用户有机会检查返回值并跳过他或她打算在当前面板中执行的任何操作:

If you return nil, you give the user the opportunity to check the return value and skip anything he or she intended to do with the current panel:

panel := XYZ.currentPanel;
if Assigned(panel) and (panel.Index = 17) then
begin

上面的代码运行时没有任何不必要的中断。

如果立即引发异常,则不会给用户提供机会找出是否有当前面板。换句话说,引发异常将为时过早

If you immediately raise an exception, you don't give the user the opportunity to find out if there is a current panel at all. In other words, raising an exception would be premature. The same code as above will blow up.

但是我承认这是我的个人喜好(可能是很多,但不是全部)。

But I admit that this is my personal preference (and probably that of many, but not all). This is a matter of opinion.

但不要返回 nil ,您还可以公开 PanelCount 属性。如果人们需要检查类似的东西,那么如果计数为零,那么如果有人尝试访问面板,您也可以提出建议。

But instead of returning a nil, you could also expose a PanelCount property. If people have something like that to check, you can just as well raise if someone tries to access a panel if count is zero. Then it is not premature.

如您所见,有几种方法可以做到这一点。

As you can see, there are several ways to do this.

正如SilverWarrior在评论中正确注意到的那样, currentPanel 是一个已发布属性,该属性最终将出现在对象检查器中。这样可以处理返回 nil 的属性,但不一定是引发异常的属性。

As SilverWarrior correctly noticed in a comment, currentPanel is a published property which will eventually appear in an Object Inspector. That can handle a property returning nil, but not necessarily a property that throws an exception.

所以:最好建议返回 nil

这篇关于什么时候提出例外?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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