160 likes | 294 Views
C Exceptions Example. Consider a program using a Number classWe've not covered class member functions in detail yetClass member functions are much like plain-old" functionsBut are given a hidden extra pointer to the object (this") One of the class member functions is operator /=Divides valu
E N D
1. 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
2. C++ Exceptions Example Consider a program using a Number class
We’ve not covered class member functions in detail yet
Class member functions are much like “plain-old” functions
But are given a hidden extra pointer to the object (“this”)
One of the class member functions is operator /=
Divides value object contains by another passed value
Problem: what if someone passes 0 to this function?
3. 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
4. C++ Exception Syntax void foo() throw (int) {
throw 2;
}
catch (int &i) {
cout << i << endl;
}
catch (...) {
cout << “another exception” << endl;
} Can throw any type
Can specify what a function (only) throws in it’s declaration
Can catch and use exceptions in code
“Default” catch block
5. What’s in a Stack Frame? In general, structure is common A chunk of memory representing the state of an active function call Pushed on program call stack at run-time g++ -s gives assembler output can be used to deduce exact structure for a given platform Contains: The previous frame pointer The return address for the call (i.e., just after the point from which it was called) Parameters passed to the function Automatic (stack) variables for the function