This week only. Pastebin PRO Accounts Christmas Special! Don't miss out!Want more features on Pastebin? Sign Up, it's FREE!
Guest

Rolling my own exceptions

By: a guest on Feb 27th, 2012  |  syntax: None  |  size: 1.11 KB  |  views: 18  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. class MyException : public std::exception(?)
  2. {
  3. public:
  4.     enum Status
  5.     {
  6.         ERROR_FOO,
  7.         ERROR_BAR,
  8.         ...
  9.     };
  10.  
  11.     MyException(const std::string& error, Status code) :
  12.         error_(error), code_(code)
  13.     {
  14.         ...
  15.     }
  16.  
  17.     virtual const char* what() const
  18.     {
  19.         return error_.c_str();
  20.     }
  21.  
  22.     Status code() const
  23.     {
  24.         return code_;
  25.     }
  26. private:
  27.     std::string error_;
  28.     Status code_;
  29. };
  30.        
  31. throw MyException("Ooops!", MyException::ERROR_BAR);
  32.        
  33. class MyException : public std::exception
  34. {
  35. public:
  36.     enum Status
  37.     {
  38.         ERROR_FOO,
  39.         ERROR_BAR,
  40.         ...
  41.     };
  42.  
  43.     MyException(const char* error, Status code) :
  44.         std::exception(error),
  45.         code_(code)
  46.     {
  47.         ...
  48.     }
  49.     ...
  50. private:
  51.     Status code_;
  52. };
  53.        
  54. // What is a no throw operation.
  55. virtual const char* what() const throw ()
  56. {
  57.     return error_.c_str();
  58. }
  59.        
  60. class MyException: public std::runtime_error
  61. {  // STUFF  .. Put all the error message stuff here
  62. };
  63.  
  64. class MyFOO_Exception: public MyException
  65. {  // STUFF
  66. };
  67.  
  68. class MyBAR_Exception: public MyException
  69. {  // STUFF
  70. }
clone this paste RAW Paste Data