Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need for try catch within a constructor

The link http://gotw.ca/gotw/066.htm states that

Moral #1: Constructor function-try-block handlers have only one purpose -- to translate an exception. (And maybe to do logging or some other side effects.) They are not useful for any other purpose.

While http://www.parashift.com/c++-faq-lite/exceptions.html#faq-17.8

If a constructor throws an exception, the object's destructor is not run. If your object has already done something that needs to be undone (such as allocating some memory, opening a file, or locking a semaphore), this "stuff that needs to be undone" must be remembered by a data member inside the object.

Are these 2 statements not contradictory? The first one kind of implies that the try catch within a constructor is pretty much useless while the second says that it is needed to free resources. What am i missing here?

like image 462
koobi Avatar asked Jun 23 '26 00:06

koobi


1 Answers

Moral #1 talks about function-try-block & the second statement talks about a normal try catch block, both are distinctly different.

You need to understand the different between the two to understand how the two sentences make sense. This answer here explains that.

like image 115
Alok Save Avatar answered Jun 25 '26 14:06

Alok Save



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!