user3810155
user3810155

Reputation:

Can C++ disambiguate the type of an exception object?

With empty exception objects such as,

class E1
{
};

class E2
{
};

Can C++('s compiler or the resulting executable) safely disambiguate between such exception objects in a catch statement? If so, does it mean that a type code for each exception object should be stored and tracked internally?

Upvotes: 0

Views: 49

Answers (2)

Daws
Daws

Reputation: 702

Yes, the C++ runtime will choose the appropriate catch block based on the type of the exception thrown. You can use multiple catch blocks to handle different types of exceptions

try 
{
    throw E2();
}
catch (E1)
{
    std::cout << "Caught E1";
}
catch (E2)
{
    std::cout << "Caught E2";
}

// Output: "Caught E2"

Upvotes: 3

Sam Varshavchik
Sam Varshavchik

Reputation: 118300

The short answer is yes. E1 and E2 are distinct and separate classes. What they contain, is immaterial.

Upvotes: 1

Related Questions