Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constructors and Exceptions

Tags:

c++

I was reading some notes on C++ and came across the following question

Q: Can a constructor throws an exception? How to handle the error when the constructor fails?

A:The constructor never throws an error.

Now this answer kind of confused me and just to make sure I went online and read that you could always throw exceptions from a constructor. I just wanted to make sure if this way a typo in the notes and that I may not be missing something important.

like image 560
MistyD Avatar asked Apr 15 '26 03:04

MistyD


1 Answers

The notes are wrong, if they're talking about constructors in general. Ctors can indeed throw normally. Perhaps that was discussing a particular class which guarantees nonthrow construction?

On the other hand, it's strongly encouraged to code so that your destructors never throw. It's legal for them to do so, but throwing an exception during stack unwinding results in immediate program termination (a call to std::terminate).

like image 162
Angew is no longer proud of SO Avatar answered Apr 17 '26 16:04

Angew is no longer proud of SO



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!