Throw an exception in a constructor

Question posted in Computer Software on 08 2010
Rate question difficulty level 0 Votes
hat happens if you throw an exception in a constructor???
 
 
2 Answers
 
My response: I don't do things in a constructor that would cause an expection to be thrown. I use initialization and reset functions to do all of my allocates and deallocates and dangerous stuff. Defensive programming is necessary even in garbage colelction languages. It teaches valdiation before usage and error/exception handling. If you ever do small device work, you learn to valdiate everythign as you do not necessarily have virtual memory, or other resources at your disposal.

Problem is most folks who I've run into (+60%) who do C++ do not know anything abotu security programming, do not validate any potential exception calls, do not validate input to their itnerfaces, do not understand have to track allocated memroy and check for buffer overflow issues, etc. C++ is an exceptional language especialyl for cross platform work (which I do a lot of). You just need to know how to use your tools. Same with .NET, or any other tools/frameworks/etc that folks use.

08/12/2010
 
 
This is one of those topics that people have wildly varying opinions on. I don't like the idea of having Initialize methods. It makes it too easy to create a partially initialized object. But throwing exceptions in your constructor means you have to wrap your new()'s in a try/catch block all the time, which is ugly. So there really isn't one perfect answer to this question.

You should probably do your best to refrain from performing risky operations in a constructor that might cause exceptions, but what if your constructor takes a parameter and that parameter is invalid (i.e. null, empty, out of range, etc.)?


I believe that a constructor's purpose is to completely initialize an object. If it fails to do that, and there's no way to handle it, then an exception is what's needed.

11/06/2010
 
 
Add an answer*
 
Your name
Email
 
Location: United States
object oriented c++ c# .net

add a question

arrow_blue


Now hiring!
---------------------------
---------------------------
---------------------------
---------------------------
Mercer 
---------------------------
---------------------------
---------------------------