Error Handling ------------------ return value from main exit(int) terminates program run, clean, graceful flush buffers, close files execute destructors for statically allocated object exit(0) means no errors abort() ugly termination, ends program assert(condition) if condition true, nothing happens, program continues if condition false, program aborts, prints data (file, line, assert) Point2D *parray; parray = new Point[6000]; if (!parray) { cerr << "not enough memory for point array" << endl; exit(1); } assert(parray); Exception Handling -------------------- - an exception is a value that indicates a problem - it can be of any data type "try" block put around code that will eventually throw an exception "catch" phrase for each exception you want to handle follows try block put handling code can further throw the exception that you caught "throw" exception object where you find an error or problem If try block throws exception not caught, std::terminate called (which calls abort if main is reached) Declare which exceptions a function can throw in the header: void func(int param) throw (char, domain_error) void func(char thing) throw() // means can't throw any void func() // no throw means can throw anything If function throws exception not declared, then std::unexpected called Compiler doesn't care if you declare or not Class inheritance hierarchy for standard exception classes: - built-in exception classes: exception bad_alloc, bad_cast, bad_typeid, bad_exception, ios_base::failure logic_error domain_error, invalid_argument, length_error, out_of_range runtime_error range_error, overflow_error, underflow_error - every exception object has message (const char *): e.what() - constructors for exceptions have string argument (for message) - can derive your own exception classes - catch parameters must be passed by reference to take advantage of inheritance catch (...) // to catch anything not yet caught, any data type { } Don't use exceptions with templates! When to use: - no next or prev for iterator - delete from empty container - Set - if duplicate occurs - data validity for class objects - memory allocation - index ranges