When to raise an exception?

时光怂恿深爱的人放手 提交于 2020-01-05 07:16:07

问题


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;

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?

  • 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).

回答1:


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

The above code runs without any unnecessary interruptions.

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.


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.

Note

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.

So: the best advice is to return nil.



来源:https://stackoverflow.com/questions/55891739/when-to-raise-an-exception

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!