Skip to main content

[C++] Handling Exceptions in Constructors

When you use RAII idiom, there are often situations where constructors have to do complex tasks. These complex tasks can sometimes fail, resulting in throwing exceptions. This raises a concern: Is it okay to throw exceptions in constructors?

The first concern is memory leaks. Fortunately, memory leaks do not occur. Variables created on the stack are released through stack unwinding, and if an exception occurs during heap allocation with the new operator, the new operator automatically deallocates the memory and returns nullptr.

The next concern is whether the destructor of the member variables will be called correctly. However, this is also not a problem. When an exception occurs, member variables can be divided into three categories: fully initialized member variables, member variables being initialized, and uninitialized member variables. Fully initialized member variables have had their constructors called and memory allocations completed successfully. In the example code, this applies to the variable b. When an exception occurs, these variables have their destructors called and resources released properly.

Member variables being initialized, like c in the example code, are those in the middle of initialization when an exception occurs. If an exception occurs during member variable initialization, as in the code above, there is only one such variable. However, no member variables are initialized if an exception occurs in the constructor body.

Lastly, uninitialized member variables do not have their constructors called, so their destructors are not called either. However, this is correct behavior since their constructors have not been called yet.

What about inheritance? Will resources allocated by the parent class be released properly? Of course, there is no problem in this case either. When an exception occurs in a constructor, after the destructors of all fully initialized member variables have been called, the parent class's destructors are called to release resources. Thus, executing the code above will produce the following output.

Returning to the initial question: Is it okay to throw exceptions in constructors?

As seen above, there is no problem...... I hope to say. However, one assumption is required: If the class is well-designed, there is no problem with throwing exceptions in constructors.

So, what is a poorly designed class, and what problems can arise in such cases?

In the code above, the constructor of the class B allocates an A object on the heap and explicitly calls delete in the destructor to release it. If no exception occurs in the constructor, there is no problem. When B is allocated, and if an exception occurs, A is allocated, and when B is destroyed, A is destroyed as well.

However, if an exception occurs in B's constructor, a problem arises. When cleaning up B's member variables, the destructor of A is not called because a is merely a pointer to A. Moreover, since B has not been initialized, its destructor is not called, and a becomes a leaked memory. To prevent this, the lifetime of A should be matched to that of B, as the below code.

This article is the translation of my Korean post written in 2017. Looking back at it now, it is a good example of the importance of choosing meaningful variable names. I apologize for using example code with names like A, B, a, and b.


Popular posts from this blog

Type Conversion in Rust

Type conversion is not special in Rust. It's just a function that takes ownership of the value and returns the other type. So you can name convert functions anything. However, it's a convention to use as_ , to_ , and into_ prefixed name or to use from_ prefixed constructor. From You can create any function for type conversion. However, if you want to provide generic interfaces, you'd better implement the From trait. For instance, you should implement From<X> for Y when you want the interface that converts the X type value to the Y type value. The From trait have an associated function named from . You can call this function like From::from(x) . You also can call it like Y::from(x) if the compiler cannot infer the type of the destination type. Into From have an associated function, it makes you be able to specify the destination type. It's why From has an associated function instead of a method, but on the other hands, you cannot use it as a me

Do not use garbage collection to catch memory leak

Garbage collection is a technique that automatically releases unnecessary memory. It's very famous because many programming languages adopted garbage collection after John McCarthy implemented it in Lisp. However, there are a few people who misunderstand what garbage collection does. If you think garbage collection prevents a memory leak, unfortunately, you are one of them. Garbage collection cannot prevent a memory leak. There is no way to avoid all memory leaks if you are using Turing-complete language. To understand it you should know what a memory leak is. Wikipedia describes a memory leak as the following: a type of resource leak that occurs when a computer program incorrectly manages memory allocations in such a way that memory which is no longer needed is not released. Briefly, a memory leak is a bug that doesn't release a memory that you don't use. So it is first to find the memory which will not be used in order to detect memory leaks. Unfortunately, it i