Exception Handling - Example 15 - Standard Exceptions

// File: eh15.cpp - Standard exceptions

#include <iostream>
#include <string>
#include <exception>
#include <new>
#include <typeinfo>	// for bad_cast
#include <stdexcept>
using namespace std;

class base {
public:
	virtual void funk() {}
};

class derived : public base {
public:
	void funk() {}
};


int main()
{
	// test bad_alloc
	try
	{
		while (1)
		{
			cout << "Can I have some memory?\n";
			new char[0x7fffffff];
		}
	}
	catch(bad_alloc error)
	{
		cerr << error.what() << endl;
	}
	
	// test bad_cast
	try 
	{
		base		baseObject;
		// try to cast a base object to a derived object
		derived& ref2derived = dynamic_cast <derived&>(baseObject);
	}
	catch(const bad_cast& error)
	{
		cerr << error.what() << endl;
	}

	// test out_of_range error
	try {
		string S = "Hey";
		cout << "S.at(2)=" << S.at(2) << endl;
		cout << "S.at(5)=" << S.at(5) << endl;	// string throws an out_of_range error
	}
	catch (const out_of_range& error) {
		cout << "Exception: " << error.what() << endl;}

	catch (exception& e) {
		cout << "Exception: " << e.what() << endl;
	}
	catch (...) {
		cout << "I'm there\n";
	}
	cout << "*** End of Program ***\n";
	return 0;
}

***** Program Output ***** MS Visual C++ 2008
Can I have some memory?
bad allocation
Bad dynamic_cast!
S.at(2)=y
Exception: invalid string position
*** End of Program ***
***** Program Output ***** gnu g++ version 3.4.2
Can I have some memory?
St9bad_alloc
St8bad_cast
S.at(2)=y
Exception: basic_string::at
*** End of Program ***