Thursday, February 10, 2011

C++ Exception

Exception is consist of detection and handling.

When an exception happens, program stops, finds where to handle, handles exception, and resumes from where it handled an eception.

Class, integer or string can be an exception object to be thrown.

Throwing an exception is done by

throw exceptionObject;

Try always goes with catch.

try {
throw "happened!";
}
catch (const char *msg) {
}
catch (...)
{
// handles all exceptions.
}


Exception can be sent to upper routine after handling.

catch (...) {
// handles exception
...
throw; // propagates again for the other handler
}


If no handler found, program ends with terminate().

Thinks

When a class constructor fails, only exception can make it known to the program.

Use of exception reduces 'if ... else ...' statements.

// Before,
if (condition) {
// do something
}
else {
// handle by itself
}

// After,
check_condition(); // raise exception.
// do something

Level of exception handler in the program is where it knows the exception and the way to handle it.(In other words, it's good to propagate an exception to the upper routine when it's not adequate to handle it there.)

Exception is different from hardware exception like seg-fault. That means there's 'throw' codes in the program.

This kind of handling code of resource releasing is not that good.

// not a good example.
try {
// alloc something.
}
catch (...) {
// release them.
throw;
}


Instead, resource alloc, release routine is good to be in the constructor, destructor code of the class("Resource aquisition is initialization" - Bjarne Stroustrup). "Because exception handling guarantees to call all destructors of local variables".

Standard exceptions.
C++ offers 'exception' basic class. This class has a virtual function 'what()' which returns const char * so, we can know what's going on during an exception with this message(throw() means this function will not throw an exception).
class exception {
public:
virtual const char * what() const throw();
...
}


So if your code has a catch statement like below, it catches all kinds of standard exception which inherits from the exception class.

catch (const std::exception &ex) {
std::cout << ex.what() << std::endl;
}
Notes

Auto pointer.

#include <memory>
...
auto_ptr p(new AClass); // will be released automatically.