100 likes | 206 Views
Review of assert. Used for error checking Example Complex* ptr = new Complex; assert(ptr); Limitations Only works in Debug mode ALWAYS exits the program. Similar Error Handler. Complex* ptr = new Complex; if (!ptr) { cerr << “Allocate failedâ€; exit(EXIT_FAILURE); }
E N D
Review of assert • Used for error checking • Example Complex* ptr = new Complex; assert(ptr); • Limitations • Only works in Debug mode • ALWAYS exits the program CS-183Dr. Mark L. Hornick
Similar Error Handler Complex* ptr = new Complex; if (!ptr) { cerr << “Allocate failed”; exit(EXIT_FAILURE); } • Other solutions • Substitute a safe alternative • e.g. A file open fails, use a default name CS-183Dr. Mark L. Hornick
Exceptions • C++’s structured solution to error handling • Java’s is almost identical • Basic mechanism • exception handling must be enabled in project properties • This is enabled by default • Code detects an error – throws an exception • Special code catches the throw CS-183Dr. Mark L. Hornick
Linked by thrown type! Exception Example void GetData(…,const string& file) { ifstream infile(file.c_str()); try { if (ifstream) { // Normal file I/O } else throw(file); } … catch(string str) { cerr << … } } CS-183Dr. Mark L. Hornick
Coding Exceptions • try • Look for exception in code block • throw • Exception found, providing data • catch • Handle exception based on type • Flexible • The function throwing doesn’t have to be the one that catches • Can be many levels up in the call stack CS-183Dr. Mark L. Hornick
Rules for Exceptions (1) • Lowest level will make the catch • If the types match • If no catch is found at any level • That matches the type • Program exits with error CS-183Dr. Mark L. Hornick
Rules for Exceptions (2) • A generic or default catch is possible • Ellipses (…) catches any type catch(…) { statements… } • Often used for cleanup • delete memory locally newed • (Destructors still called, though) • Re-throw to give caller chance to handle after local cleanup… • throw; CS-183Dr. Mark L. Hornick
Catching Allocation Errors • Without exception handling Complex* ptr = new (nothrow) Complex; • With exception handling try { … Complex* ptr = new Complex; } catch (bad_alloc b) { statements… } CS-183Dr. Mark L. Hornick
Standard Exception Hierarchy • Most thrown types are derived • From base class: exception • Found in #include <exception> CS-183Dr. Mark L. Hornick
Predefined Exceptions • <stdexcept> • runtime_error • e.g. overflow_error, underflow_error • logic_error • e.g. invalid_argument, length_error, out_of_range • Others • bad_alloc, bad_typeid, bad_exception CS-183Dr. Mark L. Hornick