[Insight-users] throwing exception inside constructor
Luis Ibanez
luis.ibanez at kitware.com
Wed Oct 17 08:36:19 EDT 2007
Hi Ziv,
Throwing exceptions from constructors is in general discouraged.
It is easy to end up with partially constructed objects.
See for example:
http://nedbatchelder.com/blog/20041202T070735.html
http://www-128.ibm.com/developerworks/library/l-cppexcep.html?ca=dnt-68
---
On the design side:
Given that you are creating an object deriving from the
LightObject, your only way to create that object is via
the ::New() method.
and, since there are *no parameters* on this method,
we are wondering:
"How is it possible for the object constructor
to get into an error condition so sever that
it justifies throwing an exception ?"
It is likely that you are overreaching in the amount
of tasks the constructor is performing, and that you
should probably consider more a model of the sort:
MyObject::Pointer letMeLive = MyObject::New();
try
{
letMeLive->Initialize();
}
catch( ... )
{
// ...etc
}
Regards,
Luis
-----------------
Ziv Yaniv wrote:
> Hi all,
>
> I would like to throw an exception from an object that is part of the
> itk::LightObject hierarchy (see short program below). For some reason
> once I throw the exception the program crashes, even though all possible
> exception types should be caught.
> Is there a standard way of throwing exceptions from an itk constructor,
> or is this something that should never be done in itk (if so why)?
> Working platform is wintel, with the visual studio 8.0 compiler.
>
> insights are appreciated
> Ziv
>
> #include "itkCommand.h"
>
> class MyClass : public itk::Command
> {
> public:
> MyClass(int i) throw (std::runtime_error)
> {
> if(i<0)
> {
> throw std::runtime_error("got negative");
> }
> this->i =i;
> }
> virtual void Execute(itk::Object *caller,
> const itk::EventObject & event ) {}
> virtual void Execute(const itk::Object *caller,
> const itk::EventObject & event ){}
>
> virtual void Delete()
> {
> itk::Object::Delete();
> }
> void Print()
> {
> std::cout<<i<<"\n";
> }
> private:
> ~MyClass(){}
> int i;
> };
>
> int main(int argc, char *argv[])
> {
> int i = -1;
>
> try {
> MyClass *m = new MyClass(i);
> m->Print();
> } //what I expect
> catch(std::runtime_error &re) {
> std::cout<<re.what()<<"\n";
> } //maybe an itk exception
> catch(itk::ExceptionObject &eo) {
> std::cout<<eo.what()<<"\n";
> } //last resort
> catch(...) {
> std::cout<<"caught exception\n";
> }
> }
>
>
More information about the Insight-users
mailing list