I am currently using Visual Studio Express C++ 2008, and have some questions about catch block ordering. Unfortunately, I could not find the answer on the internet so I am posing these questions to the experts.
I notice that unless catch (…) is placed at the end of a catch block, the compilation will fail with error C2311. For example, the following would compile:
catch (MyException)
{
}
catch (...)
{
}
while the following would not:
catch (...)
{
}
catch (MyException)
{
}
a. Could I ask if this is defined in the C++ language standard, or if this is just the Microsoft compiler being strict?
b. Do C# and Java have the same rules as well?
c. As an aside, I have also tried making a base class and a derived class, and putting the catch statement for the base class before the catch statement for the derived class. This compiled without problems. Are there no language standards guarding against such practice please?
According to the standard, the order is significant. Basically the first catch that matches the exception will be caught.
a) Because
catch(...)will make any following catches irrelevant, the standard only allows it to be the last catch.b) C# and Java have similar rules.
c) catch (by reference or pointer) of a base before a derived class will make the code for the derived irrelevant. However, the standard does allow this