We pay for user submitted tutorials and articles that we publish. Anyone can send in a contributionLearn More
Is it OK to throw exceptions from constructors? Some of us may have heard that it is wrong but don’t really remember why. There are lots of philosophical arguments about this question, you may become confused trying to understand what’s the right thing to do. Does it mater if we are developing with C++ or any other .Net language like C#? I am writing this article to shed some light on the “throwing exceptions from constructors” topic.
Constructors can’t return values, so we pretty much have to throw an exception to indicate that the object couldn’t be constructed. Some of you may grasp that constructors are supposed to handle simple tasks like initialization and if someone is up to the stage where he needs to throw exceptions from constructor, reviewing his code would be a better idea. I don’t agree with that! When we get parameters to a constructor, we may need to check their validity. How would you notify about an invalid parameter? As I already said, constructors can’t return values, and I really don’t think that adding an Init() method is a good idea - it is an error prone model that permits partially constructed objects to exist.
I know that exceptions were initially invented and designed specifically to support failures in constructor. You can read Bjarne Stroustrups (who designed and implemented the C++ programming language) presentation about “Standard-Library Exception Safety” and read page 36 to see it in your own eyes. It’s reasonable for a constructor to throw an exception as long as it cleans itself up properly. If you follow the RAII paradigm (Resource Acquisition Is Initialization) then it is quite common for a constructor to do meaningful work. So, it is OK to throw exceptions from constructors in C++. Just don’t throw them from destructors…
In .Net and C# specifically, there is no single reason to avoid this behavior - the finalizer will be called even on exceptional construction. Besides that, exceptions are thrown from constructors everywhere in the .Net Framework, just look at Guid, DateTime, Queue, FileStream and many other .Net constructors. So, it is OK to throw exceptions from constructors in C# too.
Do you throw exceptions from constructors?
Copyright © 2012 Dev102.com
Breeze : Designed by Amit Raz and Nitzan Kupererd