Here's a curious one. I have a class A. It has an item of class B, which I want to initialize in the constructor of A using an initializer list, like so:
class A { public: A(const B& b): mB(b) { }; private: B mB; };
Is there a way to catch exceptions that might be thrown by mB's copy-constructor while still using the initializer list method? Or would I have to initialize mB within the constructor's braces in order to have a try/catch?
When throwing an exception in a constructor, the memory for the object itself has already been allocated by the time the constructor is called. So, the compiler will automatically deallocate the memory occupied by the object after the exception is thrown.
You would catch the exception in the calling code, not in the constructor. Exceptions aren't returned in the same way as return values, they skip up the stack to the first appropriate catch block, so whilst you can't return a value from the constructor you can throw an exception from it.
When an object is created inside a try block, destructor for the object is called before control is transferred to catch block. Question 9 Explanation: The destructors are called in reverse order of constructors. Also, after the try block, the destructors are called only for completely constructed objects.
The throw keyword throws an exception when a problem is detected, which lets us create a custom error. The catch statement allows you to define a block of code to be executed, if an error occurs in the try block.
Have a read of http://weseetips.wordpress.com/tag/exception-from-constructor-initializer-list/)
Edit: After more digging, these are called "Function try blocks".
I confess I didn't know this either until I went looking. You learn something every day! I don't know if this is an indictment of how little I get to use C++ these days, my lack of C++ knowledge, or the often Byzantine features that litter the language. Ah well - I still like it :)
To ensure people don't have to jump to another site, the syntax of a function try block for constructors turns out to be:
C::C() try : init1(), ..., initn() { // Constructor } catch(...) { // Handle exception }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With