-(dearvoid@LinuxEden:tty3)-(~/void/c++)-
[4013 0] # cat exception.cc
#include <iostream>
using namespace std;
class MyException {
public:
MyException() {}
MyException(const string & s) : errMsg(s) {}
const string & getMsg()
{
return errMsg;
}
void setMsg(const string & s)
{
errMsg = s;
}
private:
string errMsg;
};
void throwExecption_1(const string & s)
{
throw MyException(s);
}
void throwExecption_2(const string & s)
{
static MyException e;
e.setMsg(s);
throw &e;
}
int main()
{
try {
throwExecption_1("Oops 1!");
} catch (MyException & e) {
cout << e.getMsg() << endl;
}
try {
throwExecption_1("Oops 2!");
} catch (MyException e) {
cout << e.getMsg() << endl;
}
try {
throwExecption_2("Oops 3!");
} catch (MyException * e) {
cout << e->getMsg() << endl;
}
try {
throwExecption_2("Oops 4!");
} catch (MyException * & e) {
cout << e->getMsg() << endl;
}
}
-(dearvoid@LinuxEden:tty3)-(~/void/c++)-
[4013 0] # g++ -o exception exception.cc
-(dearvoid@LinuxEden:tty3)-(~/void/c++)-
[4013 0] # ./exception
Oops 1!
Oops 2!
Oops 3!
Oops 4!
-(dearvoid@LinuxEden:tty3)-(~/void/c++)-
[4013 0] # o