Practice mode C++

Why is it recommended to catch exceptions by reference, as in catch (const std::exception& e)?

Correct answer A. To avoid copying and object slicing so the derived exception's behaviour is preserved

Explanation

Catching by value copies the exception object, and if a derived exception such as std::out_of_range is caught as std::exception by value, it is sliced: overridden virtual functions like what() then act on only the base part. Catching by const reference avoids both the copy and slicing, and lets one handler process a whole hierarchy of exception types correctly.

Report a problem

Answer checked How we write and check questions

Tip: press A, B, C or D to answer, and N for the next question.

Advertisement

Have a question about this answer?

Your email address will not be published. Required fields are marked *

Links and website addresses are not allowed in comments.