Exceptions

Exceptions are used to report exceptional conditions, such as invalid input to a function or a missing resource. Best practices vary widely between languages, but generally exceptions are used to indicate problems that don't fit into the standard flow of a program.

Because of this, exceptions generally traverse up the stack of a program to a point where an error handler is defined for that particular exception. This is important because it allows error handling to be separate from main functionality. It also allows a program to define error handling code at a place where there is enough information to deal with the error correctly.

struct MyException
{
	// Any data relevant to the exception
};

// This function throws an exception
void foo()
{
	throw MyException();
}

try {
	foo();
}
catch (MyException &exc)
{
	// Handle the error
}

Many languages such as Ruby, Java and Python support some kind of exception handling. Some languages provide more general language facilities such as coroutines which can be used to implement exceptions.

Further Reading