XHLin
XHLin

Reputation: 321

How to deal the null pointer without exit?

When i got the null pointer, is there a better way to deal the null point instead of MessageBox and exit? My teacher told me it is not a good way to use exit(). Here is my code:

CCheckBoxUI *pCbSwitch = static_cast<CCheckBoxUI*> (pItem->FindSubControl(_T("switch")));
    ASSERT(pCbSwitch && "Failed to find contronl");
    if (pCbSwitch == nullptr)
    {
        MessageBox(NULL, _T("Failed to find contronl"), _T("tip"), 0);
        exit(-1);
    }

Upvotes: 0

Views: 153

Answers (2)

Emilio Garavaglia
Emilio Garavaglia

Reputation: 20730

Can pItem->FindSubControl(_T("switch")) really fail?

unless you don't have other function adding or removing subcontrols form your one ... the only failure can be a typo in the control name.

This is not "normal behavior" but a bug that your debug version catch with the assertion. After the bug is corrected, no failure are possible, so no other check make sense.

Unless... you are in so restricted memory space that may be the framework is unable to create the control, so you cannot get it. But that's a situation you shold already know while creating the sub-controls. But in that case... even displaying a message box can be impossible!

In any case, if you want to be defensive e gracefully exit, don't call exit, but throw an exception. You can catch it in the caller (or in main) and exit in a cleaned up way.

Upvotes: 1

MSalters
MSalters

Reputation: 179809

Probably the safest way is to ignore the possible null pointer. It's your control, and you know you put a switch element on it, so you know FindSubControl will succeed. FindSubControl itself doesn't know that, which is why it documented to potentially return a null pointer.

Sure, you may have a bug, but that's why you have the assert in debug builds.

Upvotes: 4

Related Questions