[Insight-users] throwing exception inside constructor

Ziv Yaniv zivy at isis.imac.georgetown.edu
Tue Oct 16 16:38:57 EDT 2007


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";
   }
}


-- 
Ziv Yaniv, PhD., Research Assistant Professor
Imaging Science and Information Systems (ISIS) Center
Department of Radiology
Georgetown University Medical Center
2115 Wisconsin Avenue, Suite 603
Washington, DC, 20007,

Phone: +1-202-687-7286
Fax: +1-202-784-3479
email: zivy at isis.imac.georgetown.edu
web: http://isiswiki.georgetown.edu/zivy/



More information about the Insight-users mailing list