Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catching exceptions from a constructor's initializer list

Tags:

c++

exception

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?

like image 673
Head Geek Avatar asked Oct 01 '08 22:10

Head Geek


People also ask

How do you handle exception if it comes in calling of constructor?

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.

How do you handle exceptions that arise in constructors explain with an example?

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.

What will happen in case of destructor if the exception is raised inside the try block?

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.

What is throw and catch in C++?

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.


1 Answers

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 } 
like image 67
Adam Wright Avatar answered Oct 17 '22 02:10

Adam Wright