3
3Programming IIObject-Oriented Programming Exception DEFINITION [Exception] An exception is a run-time error. Examples: not enough memory, a file cannot be opened, invalid object received for an operation, etc. How to deal with exceptions? terminate the program => not appropriate return a value representing “error” => what is an acceptable error code? It has to be checked by the caller. return a legal value and leave the program in an illegal state => caller has to test an errno state variable call a function supplied to be called in case of “error” => no control over caller’s code Useful, ordinary code is mixed with error-handling code => less readable programs, hard to maintain => programs become “brittle”

4
4Programming IIObject-Oriented Programming Exception handling DEFINITION [Exception handling] Exception handling is a mechanism that allows two separately developed program components to communicate when a program anomaly, called an exception, is encountered during the execution of the program. OOP error handling style provides programmers with a way of handling errors where they are most naturally handled Designed to handle only synchronous exceptions; asynchronous exceptions require fundamentally different approaches. Exception-handling mechanism in C++ is a non-local control structure based on stack unwinding that can be seen as an alternative return mechanism. There are legitimate uses of exception that have nothing to do with errors.

8
8Programming IIObject-Oriented Programming Catching exceptions Handler H is invoked when: [1] if H is the same type as E [2] if H is an unambiguous public base of E [3] if H and E are pointer types and [1] or [2] holds for the types to which they refer [4] if H is a reference and [1] or [2] holds for the type to which H refers. void f() { try { throw E(); } catch(H) { } const can be used to denote exceptions that are not modified Example: catch(const MathException& e) { /* */ } In principle, exceptions are copied when it is thrown so that the handler gets a copy of the original. Re-throw an exception void f() { try { } catch(MathException& e) { if(cannot_handle_it_completely) throw; // re-throw an exception else // do the job & consume the exc. } REMARKS Order of handlers is important. Why? catch(…) – catches any exception because ellipsis indicates ‘any argument’

14
14Programming IIObject-Oriented Programming Exceptions in members initialization Problem: what happens if a member initialization throws an exception? The constructor can catch this kind of problems by using try-catch block in its initialization list. Example class X { Vector v; public: X(int size); }; X::X(int size) try : v(size) // initialize v by size { } catch(Vector::BadSize) { } { } Copy-constructors and assignment operators are special case of constructors/operators because they are invoked automatically, they deal with acquiring + releasing of resources

15
15Programming IIObject-Oriented Programming Exceptions in destructors A destructor can be called: ― [1] in ‘normal’ way, when objects are destroyed ― [2] during exception handling, when during stack unwinding a scope containing an object with destructor is exited Use uncaught_exception() function to decide whether the destructor was called due to case [1] (returns false) or [2] (returns true). In the later case, if an exception “escapes” from the destructor then std::terminate() function is called to signal an abnormal program termination. To protect itself from this kind of disaster, a destructor can use try- catch block. Example: X::~X() { try { // do the task that might raise an exception } catch(…) { // handle any exception here } void f() { try { X anXObject; // some operations that may generate an Exception } // => destroy anXObject, using X::~X (), in case [2] catch(Exception& e) { } X anotherXObject; } // => destroy anotherXObject, using X::~X(), in case [1]

17
17Programming IIObject-Oriented Programming Exception specifications Specify the set of exceptions that might be thrown as part of function declaration. Syntax: type name(arg_list) throw (Exceptions_list); Example: void add(Matrix& m1, Matrix& m2) throw (MathException, bad_alloc); If exception list is missing then the function can throw any exception. void f() throw(); - doesn’t throw any exception REMARKS Exception specifications must be included in both function’s declaration and definition. A virtual function can be overridden only by a function that has an exception-specifications at least as restrictive as its own. If other exception than the ones specified in exception specification is thrown => call to std::unexpected(), which – by default – calls std::terminate(), which calls abort(). User-defined handlers for std::unexpected, std::terminate using set_unexpected, respectively set_terminate functions provided in standard library.

18
18Programming IIObject-Oriented Programming Uncaught exceptions? If an exception is thrown but not caught, the function std::terminate will be called. To handle all the exceptions that can be thrown in a program, main should read like below: int main(int, char*[]) { try { // do the actual job } catch(…) { // handle any uncaught exception so far } Dynamic (run-time) detection of exceptions. Exception handling can be implemented so that there is no run-time overhead when no exception is thrown and throwing an exception is not all that expensive as compared to calling a function. C++ Standard Library exposes a hierarchy of predefined exceptions: bad_alloc, bad_cast, bad_exception, overflow_error etc., all of them derived from class exception.