Home > front end >  Handling exceptions from a Method in a dialog that can be model and modeless
Handling exceptions from a Method in a dialog that can be model and modeless

Time:11-28

This is an extract of a method in CDialog class:

void CDialog1::Method()
{
    try
    {
        // Snip
    }
    catch (CException* e_)
    {
        const gsl::not_null<CException*> e{ e_ };
        e->ReportError();
        e->Delete();
    }
    catch (const _com_error& e)
    {
        AfxMessageBox(e.ErrorMessage(), MB_OK | MB_ICONERROR);
    }
}

There is no issue with this function when it is ran from an instance of the modal dialog.


But, in another part of my application I load the same dialog as a hidden modeless dialog. And I call the same function. Eg:

void CDialog2::SomeTask()
{
    if (m_pDialog1 != nullptr)
    {
        m_pDialog1->Method();
    }
}

In this second scenario there is an issue with Method when an error is encountered. CDialog2 needs to handle the display of the errors from what I understand, because the hidden instance will appear if it shows a messagebox.

How do I get around this? Note that CDialog1 has a boolean method IsHiddenMode so we know if we are running it as a model or not.

What is the easy way to change my methods to cater for both scenarios:

  • When CDialog1 calls the method in it's modal dialog.
  • When CDialog2 calls the method using the modeless member variable of CDialog1.

I tend to overcomplicate my explanations so I hope it makes sense.

CodePudding user response:

I adjusted the Method to detect if the dialog was in hidden mode and throw the exception, eg:

catch (const _com_error& e)
{
    if (IsHiddenMode())
    {
        throw;
    }
    else
    {
        AfxMessageBox(e.ErrorMessage(), MB_OK | MB_ICONERROR);
    }
}

That way, the calling dialog could catch and handle with a try / catch block.

  • Related