13exRTTI - Exception handling in C Why is exception...

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon
Exception handling in C++ Why is exception handling a good idea? What is it good for? Robustness: error recovery, or at least graceful termination Goal: separate exceptional from normal processing How is error handling done in traditional C code? 1) Returning error values from a function For example, malloc() returns null for out of memory; fopen() for unsuccessful open What = s are some problems with this approach? Clients may not check: For example, printf() returns the number of arguments successfully printed ho checks that? Not always possible to return an error value, e.g., if operator[] is out of bounds 2) Setting a global error condition flag Standard C provides errono() and perror() functions to support this But again, clients may simply ignore the error information- -Why? Error checking bulks up normal code, making it less efficent and harder to read Desiderata: separate exceptional from normal processing 3) Non-local gotos, using setjmp() and longjmp() Note that C gotos can only jump within a local block setjmp() saves a known good state in a program longjmp() will restore that state Problem: high coupling between setjmp and longjmp locales Problem for C++: setjmp/longjmp do NOT call destructors, so no object cleanup therefore error recovery is almost impossible--your objects are in a bad state Ada introduced a special syntax and semantics for exception handling Stroustrup describes exception handling for C++ (became available as of C++ 3.0) An example (from Stroustrup): class Vector { //detects out of range errors as exceptions int* p; int sz; public: class Range {}; //an excepton class, defined within class Vector if (0<=i && i < sz) return p[i]; //within range, OK throw Range(); //exception--throw a Range object } C++ uses metaphor of throwing and catching exceptions operator[] throws an exception, when it detects an out of range subscript I Who catches the exception? A caller: exception unwinds to the stack frame of a catcher
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full Document Right Arrow Icon
Image of page 2
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}

Page1 / 4

13exRTTI - Exception handling in C Why is exception...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online