Exceptions
E N D
Presentation Transcript
Exceptions for safe programming
Why Exceptions • exceptions are used to signal that something unusual has happened during program execution • when signal is sent, the control is transferred to specific place in a program designated to handle this exception • throwing the exception – the event of sending a signal • catching the exception – handling it • exception mechanism is for handling extraordinary situations: division by zero, array out of range • do not use it for ordinary transfer of control – bad style, cryptic program
Syntax • two constructs • try block – defines the program area where an exception may be thrown try { // some code throw ARGUMENT; // throwing exception // more code } • catch block (exception handler) – processes the exception catch (TYPE PARAMETER){ // exception handling code } • can be multiple catch blocks, distinguished by exception type • default exception catches all un-caught exceptions catch (...){ // exception handling code }
Operation • when the exception is thrown, control is transferred to the first catch block outside the try-block that matches the type of the thrown exception • after catch-block finishes, control is passed to the first statement past the last catch-block
Objects as Exceptions • classes can be used as exception types • can give exception a descriptive name • can be used to pass details about exception • example • empty class to give descriptive name class divide_by_zero {}; • more details to be passed class wrongNumber{ ... private: intoffendingNumber; }
Catching Outside Functions • may be useful to handle the exception outside the function where it is thrown • function is said to throw the exception • by default function may throw any exception • function prototype/head may list exceptions thrown by function, if throws anything else – special unexpected() function is invoked (by default terminates program) • syntax returnVal functionName(parameterList) throw (exceptionType); • example double safe_divide(int n, int d) throw (divide_by_zero){ if (d == 0) throw divide_by_zero(); return n/double(d); }
Catching Standard Exceptions • some pre-defined functions throw standard exceptions • need stdexcept header • at() – throws out_of_range • new – throws bad_alloc – unsuccessful allocation, possibly out of memory • example handling try{ string s=”hello”; s.at(5)=’!’; // throws out_of_range } catch(out_of_range){ cout << ”string too short!”; }
Questions on Exceptions • what are exceptions why are they needed? • what are try-block? catch-block? What does it mean to throw or catch an exception? • what is the type of an exception? • what is the default exception? how is it caught? • can an object be used to throw an exception? why is that useful? • how can an exception be thrown inside a function and caught outside it? • what are standard exceptions? What standard exceptions have we studied?