90 likes | 204 Views
Exception Handling. Dealing with errors reported from OS I/O errors network timeouts Dealing with exceptional logical situations divide-by-zero empty queue badly formatted source. Raising Exceptions. Error (return code) Routine returns success/fail code
E N D
Exception Handling • Dealing with errors reported from OS • I/O errors • network timeouts • Dealing with exceptional logical situations • divide-by-zero • empty queue • badly formatted source 0704.315 Programming Languages
Raising Exceptions • Error (return code) • Routine returns success/fail code • Caller checks and handles upon return • System interrupt/interrupt handler • Registration of (global) interrupt handler • Control passed to handler on exception • Inline clauses (throw/catch, on) 0704.315 Programming Languages
Raising ExceptionsError codes int main () { FILE * pFile; pFile = fopen("unexist.ent","r"); if (pFile == NULL) printf ("Error opening file unexist.ent: %s\n", strerror(errno)); return 0; } 0704.315 Programming Languages
Raising ExceptionsInterrupt Handler terminate_handler set_handler(terminate_handler fn); • Routine called when certain system-level condition occurs • In this case, when the terminate signal (Ctrl-C) is passed to program 0704.315 Programming Languages
Raising ExceptionsInline clauses int main() { cout << "Start.\n"; try { cout << "Inside try block.\n"; throw(100); cout << "This statement will not execute.\n"; } catch(int i) { cout << "Caught an exception!\n"; cout << "Value = " << i << endl; } cout << "End.\n"; return 0; } 0704.315 Programming Languages
Exceptions in C++ • catch (ExceptionType exceptionObject) • Dynamically registers a new exception handler • throw exceptionObject • Raises exception, passes control to latest matching catch • If none found, runtime error • Typed Exception Values • Exception can be any C++ class or built-in type 0704.315 Programming Languages
Exceptions in C++ (con’t) • throw declaration clause • Optional specification on function declaration float compute_average(float* values, int count) throw (ArithmeticError) { if (count == 0) throw ArithmeticError(“No data”); return (sum(values, count) / count); } 0704.315 Programming Languages
Exceptions in Java • Cannot throw built-ins • System throws exceptions (no mixed-paradigm system) too • Catchable and non-catchable exception hierarchies • finally clause 0704.315 Programming Languages
References • Sebesta. Concepts of Programming Languages, Chapter 13 • Stroustrup. The C++ Programming Language (3/e) 0704.315 Programming Languages