• Advertisement
Sign in to follow this  

Exception Object Scope

This topic is 4890 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

In the following code, what scope does the MyException object belong to. Does it go out of scope when the catch block is complete, the application exits or will this leak memory?
class MyException
{
private:
    std::string _message;
public:
    std::string Message() { return _message; }

    MyException(std::string error)
    {
        _message = error;
    }
};

void SomeFunction();

void main()
{
    try{
        SomeFunction();
    }
    catch(MyException e)
    {
        MessageBox(NULL,e.Message(),"ERROR",MB_OK);
    }
}

void SomeFunction()
{
    throw MyException("My error Message");
}

Share this post


Link to post
Share on other sites
Advertisement
You're better off catching by reference.

Reasons:
The exception won't be copied.
You can catch exceptions polymorphically.

A good rule is, always throw by value and catch by reference.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement