Exception HandlingIn this set of notes you will learn about:
|
Note: These notes cover Section 8.5 of the textbook, upto and including 8.5.2. Helpful extra hand-out material is available in class. |
Defensive Programming
|
Catching Run-Time Errors Without Exception Handling
int somefun(FILE *fd) { ... if (feof(fd)) return -1; // return error code -1 on end of file return value; // return normal (positive) value } int val; val = somefun(fd); if (val < 0) ... |
Catching Run-Time Errors without Exception Handling (cont'd)
int somefun(FILE *fd) { errstat = 0; // reset status variable ... if (feof(fd)) errstat = -1; // error detected return value; // return a value anyway } int somefun(FILE *fd, int *errstat) { *errstat = 0; // reset status parameter ... if (feof(fd)) *errstat = -1; // error detected return value; // return a value anyway } int somefun(FILE *fd, void handler(int)) { ... if (feof(fd)) handler(-1); // error detected return value; // return a value } |
Exception Handlers
|
Exception Handling in C++
{ public empty_queue(queue q) { ... }; ... // constructor that takes a queue object for diagnostics }; declares an empty queue exception declares a variable used to throw a "short int" exception ... ... throw eof_condition; // matches short int exception ... throw empty_queue(myq); ... throw 6; // matches int exception ... } catch (short int) { ... // handle end of file } catch (empty_queue e) { ... // handle empty queue, where e is an empty_queue object } catch (int n) { ... // handle exception of type int, where n contains number } catch (...) { ... // catch-all handler } |
Exception Handling in C++ (cont'd)
afun(); // may throw empty queue exception } catch (empty_queue) { ... // handle empty queue exception (this example passes no empty_queue object) } where afun can raise int and empty_queue exceptions, as well as subclasses of empty_queue |
Exception Handling in Java
{ public MyException() {}; public MyException(String msg) { super(msg); // let class Exception handle the message } } ... throw e; |
Exception Handling in Java (cont'd)
... } catch (MyException e) { ... // catch exceptions that are (descendants of) MyException } catch (Exception e) { ... // catch-all handler: all exceptions are descendants of Exception } finally { ... // always executed for user-defined clean-up operations } |
Exception Handling in Java (cont'd)
|