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.
To catch any exception the ellipsis operator can be used :
A good place to use exceptions is in contructors of classes to cleanup resources to avoid memory leaks.