An exception gets thrown twice from a constructor with a function-try-block

后端 未结 3 1703
眼角桃花
眼角桃花 2021-01-05 20:13

Why does the following exception thrown from the constructor of class A get caught twice, first by the catch within the constructor itself and second time by the catch in th

3条回答
  •  悲&欢浪女
    2021-01-05 21:08

    Function-try-blocks in a constructor cannot prevent exceptions. Once an exception occurs in a constructor, you have no object, and the exception must propagate. The only thing the function-try-block can do is some local clean-up.

    Constructors are indeed a very special animal with regards to function-try-blocks.

    Cf. C++11 15.3/14:

    The currently handled exception is rethrown if control reaches the end of a handler of the function-try-block of a constructor or destructor.


    Tl;dr: Do not use function-try-blocks, ever.

提交回复
热议问题