IceCold
IceCold

Reputation: 21154

When to raise an exception?

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?

Upvotes: 1

Views: 175

Answers (1)

Rudy Velthuis
Rudy Velthuis

Reputation: 28806

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.

Upvotes: 5

Related Questions