C++: Exceptions

Bjarne-stroustrup
 

This task is to give an example of an exception handling routine and to “throw” a new exception.

C++ has no finally construct. Instead you can do this in the destructor of an object on the stack, which will be called if an exception is thrown.

The exception can be of any type, this includes int’s, other primitives, as well as objects.

Defining exceptions

struct MyException
{
	// data with info about exception
};

There’s also a class std::exception which you can, but are not required to derive your exception class from. The advantage of doing so is that you can catch unknown exceptions and still get some meaningful information out. There are also more specific classes like std::runtime_error which derive from std::exception.

#include <exception>
struct MyException: std::exception
{
	char const* what() const throw() { return "description"; }
}

Note that in principle you can throw any copyable type as exception, including built-in types.

Throw exceptions

// this function can throw any type of exception
void foo()
{
	throw MyException();
}

// this function can only throw the types of exceptions that are listed
void foo2() throw(MyException)
{
	throw MyException();
}

// this function turns any exceptions other than MyException into std::bad_exception
void foo3() throw(MyException, std::bad_exception)
{
	throw MyException();
}

Catching exceptions

try {
	foo();
}
catch (MyException &exc)
{
	// handle exceptions of type MyException and derived
}
catch (std::exception &exc)
{
	// handle exceptions derived from std::exception, which were not handled by above catches
	// e.g.
	std::cerr << exc.what() << std::endl;
}
catch (...)
{
	// handle any type of exception not handled by above catches
}

SOURCE

Content is available under GNU Free Documentation License 1.2.