C++_exceptions - CS 342: C+ Exceptions Motivation for C+...

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

View Full Document Right Arrow Icon
Copyright © 2004 Dept. of Computer Science and Engineering, Washington University CS 342: C++ Exceptions Motivation for C++ Exceptions void Number::operator/=(const double denom) { if (denom == 0.0) { // what do we do here? } m_value /= denom; } Need to handle divide by zero case Otherwise bad things happen – Program crash – Wrong results Could set value to NaN – Special “not-a-number” value – But, caller might fail to check for it Could return a “special” value – Might be a valid return value – Could still be ignored Exceptions offer a better alternative
Background image of page 1

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

View Full DocumentRight Arrow Icon
Copyright © 2004 Dept. of Computer Science and Engineering, Washington University CS 342: C++ Exceptions C++ Expression Syntax void foo() throw (int) { throw 2; } catch (int &i) { cout << i << endl; } catch (. ..) { cout << “another exception” << endl; } • Can throw any class • Specify what a function throws in it’s declaration • Can catch and use exceptions • “Default” catch block
Background image of page 2
Copyright © 2004 Dept. of Computer Science and Engineering, Washington University CS 342: C++ Exceptions Overview of C++ Exceptions • 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 – Goes until an enclosing 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
Background image of page 3

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

View Full DocumentRight Arrow Icon
Copyright © 2004 Dept. of Computer Science and Engineering, Washington University
Background image of page 4
Image of page 5
This is the end of the preview. Sign up to access the rest of the document.

This note was uploaded on 04/07/2008 for the course CSE 332S taught by Professor Smart during the Spring '08 term at Washington University in St. Louis.

Page1 / 14

C++_exceptions - CS 342: C+ Exceptions Motivation for C+...

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

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