catching exception objects by reference, temporaries, lifetime issues

前端 未结 4 873
独厮守ぢ
独厮守ぢ 2021-01-13 03:55

Consider the following code:

#include 
#include 

void foo()
{
    throw std::runtime_error(\"How long do I live?\");
}

int         


        
4条回答
  •  梦谈多话
    2021-01-13 04:21

    Kudos for trying to understand the details of the language. At the same time, IMHO, it is far more important to understand why you should catch an exception by reference (and throw it by value), than why you can.

    People typically use a hierarchy of exception classes, and catching by reference allows you to leverage polymorphism, and catch an exception of the base class, when there is no need to handle individual exception types separately. If you couldn't catch by reference, you would have had to write a catch clause for every possible type of exception that can be thrown in the try clause.

提交回复
热议问题