Labels: c++ (6) scripting (4) the perfect project (3) coding (1) firefox (1) idea (1)

Monday, April 9, 2007

Readable exceptions fun

#include <stdexcept>
#include <iostream>

class Class
{
public:
   struct Exception
   {
      struct Any : public std::exception {};
      struct CannotConstruct : public Any {};
   };

   Class() { throw Exception::CannotConstruct(); }
};

void iKnowAboutClassAndItsConstruction (void)
{
   try
   {
      Class();
   }
   catch (Class::Exception::CannotConstruct&)
   {
      std::cout << "got Class::Exception::CannotConstruct.\n";
      // Do something... or:
      throw;
   }
}

void iKnowAboutClasses (void)
{
   try
   {
      // do something useful and specific with Class(es):
      iKnowAboutClassAndItsConstruction();
      // ...
      // ...
   }
   catch (Class::Exception::Any&)
   {
      std::cout << "got some Class::Exception.\n";  
      // Do something... or:
      throw;
   }
}

void main (void)
{
   try
   {
      // let's do something with Class(es):
      iKnowAboutClasses();
   }
   // main -- don't care about any specific exceptions but standard:
   catch (std::exception&) { std::cout << "got std::exception.\n";    }
   catch (...)             { std::cout << "got unknown exception.\n"; }
}

No comments: