9.1. Creating an Exception Class

Problem

You want to create your own exception class for throwing and catching.

Solution

You can throw or catch any C++ type that lives up to some simple requirements, namely that it has a valid copy constructor and destructor. Exceptions are a complicated subject though, so there are a number of things to consider when designing a class to represent exceptional circumstances. Example 9-1 shows what a simple exception class might look like.

Example 9-1. A simple exception class

#include <iostream>
#include <string>

using namespace std;

class Exception {

public:
   Exception(const string& msg) : msg_(msg) {}
  ~Exception() {}

   string getMessage() const {return(msg_);}
private:
   string msg_;
};

void f() {
   throw(Exception("Mr. Sulu"));
}

int main() {

   try {
      f();
   }
   catch(Exception& e) {
      cout << "You threw an exception: " << e.getMessage() << endl;
   }
}

Discussion

C++ supports exceptions with three keywords: try, catch, and throw. The syntax looks like this:

try {
   // Something that may call "throw", e.g.
   throw(Exception("Uh-oh"));
}
catch(Exception& e) {
   // Do something useful with e
}

An exception in C++ (Java and C# are similar) is a way to put a message in a bottle at some point in a program, abandon ship, and hope that someone is looking for your message somewhere down the call stack. It is an alternative to other, simpler techniques, such as returning an error code or message. The semantics of using exceptions (e.g., “trying” something, “throwing” an exception, and ...

Get C++ Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.