Skip to content

C++ Exceptions

CPP Exceptions

Creating an Exception Class

Writing 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 << "An exception was thrown : " << e.getMessage() << endl;
    }

}

Catching the base exception and logging the exception message.

catch(std::exception& e) { 
    std::cerr << "Nonspecific exception: " << e.what() << std::endl;
}

To catch any exception the ellipsis operator can be used :

catch(...) { 
    // handle exception code
}

A good place to use exceptions is in contructors of classes to cleanup resources to avoid memory leaks.

Making an Initializer List Exception safe.

class Customer { 

    public:
        Customer(int userId)
            try : currentUser(User(userId)) { 

            }
        catch(...) { 
            throw;
        }

        ~Customer() {};

    private:
        Customer();
        User currentUser;
};


int main() { 

    try { 
        Customer c(1);
    }

    catch(exception& e) { 
        cerr << "Exception : " << e.what() << endl;
    }

}