Click here to Skip to main content
15,888,461 members
Please Sign up or sign in to vote.
3.50/5 (2 votes)
See more:
I got this question in an interview.The question is, can we have exception handling in the constructor and is it safe to throw an exception from the constructor.

I tried a sample code by putting a try catch block in the constructor but I didnt get any error.Can any one please explain about this
Posted
Comments
Afzaal Ahmad Zeeshan 26-Jul-15 7:56am    
If, your constructor is based on another constructor, such as initializers for other base objects. Then, you can check whether the types were initialzed correctly.

Remember, constructors are also functions.
Sergey Alexandrovich Kryukov 26-Jul-15 11:39am    
There are two very different things: handle exceptions in a constructor or throw an exception?
—SA

Read my comment to the question, continuing from there. Remember, constructors are also functions. So, when you create a custom constructor logic you are basically trying to set up the underlying objects. If they are exposed to some errors and would work in a condition only, then yes. You need to handle the exceptions in the constructor context also.

But (IMO) it would be of no good. Suppose you are writing a constructor for an object that acts as the controller for your hardware; flash drive reader for instance. The constructor has to load the other base objects, such as connection over the ports.

C++
public:
  FlashReader() {
    // Construct the stream reader for the port
    _streamReader = streamreader::Reader(); // <-- Here
  }


Suppose, reader doesn't work, no matter of what problem. Adding a try catch block won't help you. It would be just as to prevent the application from breaking, only. Otherwise, adding a try catch block won't help you out in any way.

C++
public:
  FlashReader() {
    // Construct the stream reader for the port
    try {
       _streamReader = streamreader::Reader(); // <-- Here
    } catch (std::exception e) {
       // No difference made. 
    }
  }


That is why, although it is legal in C++ to write the try catch block. But, for what? That is the question you need to answer. Does it really matter, or is it worthy to add a try catch block, or is it just another fancy thing to maintain a dead program in the memory. :-)

For a more clearer image of the problem that might be caused with this kind of behavior, read Solution 3 by Sergey. It shows you the image, and what are the possible candidates that might be expected with this pattern.

Also, what did your term safe means? Thread-safe or what? Safety of data is a concept about instance members. If a constructor throws an exception that means no instance was created, thus no discussion to take place about safety. Throwing exception from a constructor would be a good one, I'd say. Because, it would notify the user and break the program, instead of keeping it there in the memory to create a new stack for the custom error message.
 
Share this answer
 
v3
Comments
krish0969 26-Jul-15 8:59am    
Thanks for the nice explanation.If we put the try catch block inside the constructor ,does the object is created successfully?
Dave Kreskowiak 26-Jul-15 10:11am    
In a general terms, will the object be created if there is a try/catch block in the constructor? Yes. This is easy enough for you to test on your own.

Will the object be usable? That depends on your business logic, not the existence of the try/catch block.
Sergey Alexandrovich Kryukov 26-Jul-15 11:55am    
5ed. You example and points are very good, and your advice is not very certain, which also can be considered as a benefit, because the best advice is often "use your own brain". I added some advice and attempt to show a bigger picture in Solution 3, please see.
—SA
Afzaal Ahmad Zeeshan 27-Jul-15 2:07am    
Thank you, Sergey.

That was an advice of a beginner. Indeed, it would be not very certain I will edit my answer and link it to your answer for a brief advice. :-)
Wendelius 27-Jul-15 3:41am    
Nice answer, 5.
Have a look at this page: "Exceptions and Error Handling"[^].
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 26-Jul-15 11:57am    
There are some good points in that article and some are probably missing (5ed), but — please see my comment to Solution 1 (about the value of an advice) and my Solution 3.
—SA
In addition to Solution 1: The answer could be more certain: yes and no. :-)

First of all, from your question, it is not clear what you are talking about. You are talking about handling exceptions, and in other place you are talking about throwing. Let's discuss throwing first.

Of course, it is possible to throw an exception from a constructor and then continue execution of the program in a safe way. But is it a good programming practice? Yes and no; without deep understanding of one's own design and consequences, it will likely be very bad, but it can be not bad for something well planned and designed. So, the technique should first become an object of a doubt.

The fundamental controversy is this: structured exception handling mechanism is the time machine which reverts everything to the first point of try up the stack. But what is reverted? Only the stack and the stack object, and, of course, not the side effects. The heap and the objects allocating heap and constructed is just one of such site effects, but it can be anything else.

For example, let's say, you have a constructor which creates some other objects on heap, and each of those objects also creates some other objects on heap. And, more importantly, your class is also a part of this chain, is used by some other class, and your object can also be created on heap. This is a very typical picture. Normally, you can handle an exception anywhere up the stack and have a freedom of abstracting out the exception (its location, some detail, and so on). With heap, you make your code depending on how and where the exception is thrown. The real problem is with our hypothetical "parent object" (when you develop some class for external, its use should be considered hypothetical): you can end up with half-constructed set of objects, with no way to find ends to revert the heap (that is, memory leak at best). I repeat: heap is just the most typical example of the problem.

But of course, without the side effects you can be fine. Even with the heap, if you fully control the situation in both cases, with the exception and without it. Which leads us to the problems of full exception handling inside a constructor.

What if you throw some exception is some constructor and catch it in the same constructor? (I repeat: it's not clear from your question if you meant that or not)? You will have all the same problems discussed above, only you have more control and can practically resolve the problem of correct construction in both situations (exception handled and not). But such goal would look weird. In case of handling exceptions outside of the constructor execution, you want to come to the situation where you have the object not created, and your execution context in the position as if you never tried. With handling inside a constructor, you can have it all handled, and actually created an object after an exception deeper in a constructor was thrown. I doubt the possible rationale of this design. But generally, handling exceptions too locally is a pretty bad idea. Exceptions are designed to isolate "regular" execution from exceptional. Therefore, it gives you the benefit of having very few points where you accumulate many possible exceptions on every stack, and handle the altogether. You have to strategically chose those points, and, of course, they are not in each function throwing exception.

See also my past answers:
Does Exception in C# Constructor Cause Caller Assignment to Fail?[^],
where was stored .net exceptions in operating system[^],
Unhandled Exception : Access Violation[^].

—SA
 
Share this answer
 
Comments
krish0969 26-Jul-15 14:15pm    
Thanks for providing valuable info.And I really love the way you explain it.Now I learn few more from your post :)
Sergey Alexandrovich Kryukov 26-Jul-15 21:30pm    
You are very welcome.
You touched a very class of issues with your question, and it's not very easy to explain such things in brief.
Good luck, call again.
—SA
Afzaal Ahmad Zeeshan 27-Jul-15 2:09am    
5ed, indeed your answer has a more clear view. :-)
Sergey Alexandrovich Kryukov 27-Jul-15 2:10am    
Thank you, Afzaal.
—SA
Wendelius 27-Jul-15 3:42am    
Good points, 5.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900