DOC PREVIEW
WUSTL CSE 332S - C++_statements

This preview shows page 1-2-3-4-5-6 out of 18 pages.

Save
View full document
View full document
Premium Document
Do you want full access? Go Premium and unlock all 18 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 18 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 18 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 18 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 18 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 18 pages.
Access to all documents
Download any document
Ad free experience
Premium Document
Do you want full access? Go Premium and unlock all 18 pages.
Access to all documents
Download any document
Ad free experience

Unformatted text preview:

C++ StatementsMotivation for C++ Exception StatementsC++ Exceptions: Throw Statement SyntaxC++11 Library Exception HierarchyC++ Exceptions Interrupt Control FlowExceptions Manipulate the Function Call StackIllustrating the Call Stack (1/8)Illustrating the Call Stack (2/8)Illustrating the Call Stack (3/8)Illustrating the Call Stack (4/8)Illustrating the Call Stack (5/8)Illustrating the Call Stack (6/8)Illustrating the Call Stack (7/8)Illustrating the Call Stack (8/8)More Details About Catching Exceptions in C++More About Catching Exceptions in C++Exception Specifications (do not use them)Rules of Thumb for Using C++ ExceptionsCSE 332: C++ StatementsC++ Statements•In C++ statements are basic units of execution–Each ends with ; (can use expressions to compute values)–Statements introduce scopes, e.g., of (temporary) variables•A (useful) statement usually has a side effect –Stores a value for future use: j = i + 5;–Performs input or output: cout << j << endl;–Directs control flow: if (j > 0) {…} else {…}–Interrupts control flow: throw out_of_range;–Resumes control flow: catch (RangeError &re) {…}•goto considered too low-level–Usually better to use break or continue–If you have to use goto, you must comment whyCSE 332: C++ StatementsMotivation for C++ Exception StatementsvoidNumber::operator/=(const double denom) { if (denom == 0.0) { // what to do here? } m_value /= denom;}•Need to handle cases where program cannot behave normally–E.g., zero denominator for division•Otherwise bad things happen–Program crashes–Wrong results•Could set value to Number::NaN–I.e., a special “not-a-number” value–Must avoid using a valid value… … which may be difficult (e.g., for int)–Anyway, caller might fail to check for it•Exceptions offer a better alternativeCSE 332: C++ StatementsC++ Exceptions: Throw Statement Syntaxvoid foo() { throw 2;}try { foo();}catch (int &i) { cout << “caught ” << i << endl;}catch (...) { cout << “another exception” << endl;}•Can throw any type•Can catch, inspect, use, refine, rethrow exceptions–By value makes local copy–By reference allows modifications to be made to the original exception itself•“Default” catch block is indicated by three dots–Catches every typeCSE 332: C++ StatementsC++11 Library Exception Hierarchy•C++11 standardizes a hierarchy of exception classes–To access these classes #include <stdexcept>•Two main kinds (subclasses) of exception–Run time errors (overflow errors and underflow errors)–Logic errors (invalid arguments, length error, out of range)•Several other useful subclasses of exception–Bad memory allocation–Bad cast–Bad type id–Bad exception•You can also declare other subclasses of these–Using the class and inheritance material in later lecturesCSE 332: C++ StatementsC++ Exceptions Interrupt Control Flow•Normal program control flow is halted–At the point where an exception is thrown•The program call stack “unwinds”–Stack frame of each function in call chain “pops”–Variables in each popped frame are destroyed–This goes on until a matching try/catch scope is reached•Control passes to first matching catch block–Can handle the exception and continue from there–Can free some resources and re-throw exception•Let’s look at the call stack and how it behaves–Good way to explain how exceptions work (in some detail)–Also a good way to understand normal function behaviorCSE 332: C++ StatementsExceptions Manipulate the Function Call Stack•In general, the call stack’s structure is fairly basic–A chunk of memory representing the state of an active function call–Pushed on program call stack at run-time (can observe in a debugger)•g++ -s  generates machine code (in assembly language)–A similar feature can give e xact structure for most platforms/compilers•Each stack frame contains:–A pointer to the previous stack frame–The return address (i.e., just after point from which function was called)–The parameters passed to the function (if any)–Automatic (local) variables for the function•Sometimes called “stack variables”previous frame pointerreturn addressparametersautomatic variablesCSE 332: C++ StatementsIllustrating the Call Stack (1/8)enum results {success, failure};int main (int, const char *[]) { Number n(8.1); try { n /= 0.0; cout << n << endl; } catch (int) { return failure; } return success;} •Stack frame for function main–Pushed on program call stack–With stack variable n–With parameters argc and argv•Note that parameters are initialized at frame creation•Variables are not necessarily initialized at frame creation–May occur later in called functionnm_valuemainCSE 332: C++ StatementsIllustrating the Call Stack (2/8)int main (int, const char *[]) { Number n(8.1); try { n /= 0.0; cout << n << endl; } catch (int) { return failure; } return success;} •Number constructor called–Stack frame created–Implicit this pointer points to object in previous stack framenm_valuemainthisNumber::Number(const double d)dCSE 332: C++ StatementsIllustrating the Call Stack (3/8)Number::Number(const double d) :m_value(d) {} •Enter Number constructor–m_value is set in object•How do we know which m_value to set?–Implicit this pointernm_valuemainthisNumber::Number(const double d)dCSE 332: C++ Statementsnm_valuemainIllustrating the Call Stack (4/8)Number::Number(const double d) :m_value(d) {} •Return from constructor–Its stack frame is popped–Returns to mainCSE 332: C++ StatementsIllustrating the Call Stack (5/8)int main (int, const char *[]) { Number n(8.1); try { n /= 0.0; cout << n << endl; } catch (int) { return failure; } return success;} •Call operator/= on n–New stack frame created–Copy 0.0 into call as denom–Set thisnm_valuemainthisNumber::operator/=(const double denom)denomCSE 332: C++ StatementsIllustrating the Call Stack (6/8) •Test denom against 0.0–Test succeeds–throw integer 0void Number::operator/=(const double denom) { if (denom == 0.0) { throw 0; } m_value /= denom;}nm_valuemainthisNumber::operator/=(const double denom)denomCSE 332: C++ Statementsnm_valuemainIllustrating the Call Stack (7/8) •throw unwinds call stack•Skips over rest of function•Returns to callervoid Number::operator/=(const double denom) { if (denom == 0.0) { throw 0; } value_ /= denom;}CSE 332: C++


View Full Document

WUSTL CSE 332S - C++_statements

Download C++_statements
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view C++_statements and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view C++_statements 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?