CIS-255 Home http://www.c-jump.com/bcc/c255c/c255syllabus.htm
Problem: dealing with errors is a pain, even in a simple language like C.
It's even worse in C++, where some obvious approaches don't work.
Exceptions provide a new mechanism for dealing with errors.
Fundamentally exception a control construct.
|
|
|
|
An object of any copy-able type can be an exception:
#include <iostream>
void main() {
try {
throw 20;
}
catch ( int ex ) {
std::cout << "Exception occurred: " << ex;
}
}
Avoid using native types: int, bool, and so on.
Often classes are created specifically for exceptions.
The STL provides several exception types.
// account.h
// A banking account:
class Account { /*...*/ };
// An exception class:
struct AcctError {};
|
// main.cpp
#include <iostream>
void main() {
Account acct( 1000.00 );
try {
acct.withdraw( 2000.00 );
}
catch ( AcctError& ex ) {
std::cout << "Not enough funds";
}
}
|
// account.cpp
void Account::withdraw( double amount )
{
if ( amount > m_available_balance ) {
// Not enough balance,
// Unnamed temporary object:
throw AcctError();
}
// Balance is ok, proceed...
}
|
struct AcctError
{
std::string problem;
AcctError( std::string str )
{
problem = str;
}
};
void Account::withdraw( double amount )
{
if ( amount > m_available_balance )
{
throw AcctError( "Insufficient funds." );
}
//...
}
#include <iostream>
#include "account.h"
int main()
{
Account acct;
acct.deposit( 100.00 );
try {
acct.withdraw( 1000000.00 );
}
catch ( AcctError& e ) {
std::cout << "Error: " << e.problem << endl;
return 1;
}
return 0;
}
A throw statement is syntactically like a return statement.
Execution immediately leaves the function that throws.
Local objects are all normally destroyed (like a return).
Stack is unwound, thus destroying local objects in each stack frame until catch is found.
Execution resumes with first catch statement.
When catch finished, execution continues with statements after catch.
|
|