Try catch syntax constructor

前端 未结 2 782
温柔的废话
温柔的废话 2021-01-12 11:58

http://ideone.com/UtVzxw

struct base
{
    base() { throw std::exception(); }
};

struct derived : public base
{
    derived() try : base()  { }

    catch (         


        
2条回答
  •  情书的邮戳
    2021-01-12 12:19

    Wrapping a try/catch around a superclass's constructor lets you trap exceptions that get thrown in the superclass's constructor; however the exception gets automatically rethrown when the catch block ends, and the exception continues to propagate.

    After all, the superclass did not get constructed. It threw an exception. So you can't really continue on your merry way, in the subclass's constructor, and then end up with a constructed subclass, but with a superclass that did not get constructed. That makes no sense.

    From http://en.cppreference.com/w/cpp/language/function-try-block:

    The primary purpose of function-try-blocks is to log or modify, and then rethrow the exceptions thrown from the member initializer list in a constructor. They are rarely used with destructors or with regular functions.

    This is really the primary value-added of function-try blocks: a convenient place to log "hey, this function threw an exception", that encompasses the entire function, a single place to log this kind of a thing, but without affecting ordinary exception handling.

提交回复
热议问题