Exception Specifications (C++)

From RAD Studio
Jump to: navigation, search

Go Up to Standard C++ Exception Handling

It is possible to specify which exceptions a function may throw. It is a run-time error to throw an exception of the wrong type past a function. The syntax for an exception specification is:

exception-specification:

throw (type-id-list) // type-id-list is optional
type-id-list:

type-id
type-id-list, type-id

The following examples are functions with exception specifications.

void f1(); // The function can throw any exception
void f2() throw(); // Should not throw any exceptions
void f3() throw(A, B*); // Can throw exceptions publicly derived from A, or a pointer to publicly derived B

The definition and all declarations of such a function must have an exception specification containing the same set of type-ids. If a function throws an exception not listed in its specification, the program calls the unexpected function.

You may not want to specify an exception for the following reasons:

  • First, there is a run-time performance hit on Windows for providing an exception specification for a function.
  • Second, you can get unexpected errors at run time. For example, suppose your system uses exception specifications and uses another subsystem in its implementation. Now suppose the subsystem is changed so that it throws new exception types. When you use the new subsystem code, you could get run-time errors without ever getting an indication from the compiler that this might happen.
  • Third, if you use virtual functions, you can violate the program design. This is because the exception specification is not considered part of the function type. For example, in the following code, the derived class BETA::vfunc is defined so that it does not throw any exceptions — a departure from the original function declaration.
class ALPHA {
public:
	struct ALPHA_ERR {
	};

	virtual void vfunc(void) throw(ALPHA_ERR) {
	} // Exception specification
};

class BETA : public ALPHA {
	void vfunc(void) throw() {
	} // Exception specification is changed
};

See Also