Introduction to Computer Science II
Klefstad
Exceptions
Exceptions
- useful for making code more robust
- typically for handling errors and boundary conditions
- exceptions are thrown and must be caught
- exceptions are sent to appropriate catch by type matching
Catching and Throwing Exceptions
struct Exception
{
char * message;
Exception( char *s ) : message(s) {}
};
void f( int i )
{
cout << "Entering f\n";
if ( i % 2 == 0 ) // i is even
throw Exception("I is even");
else
throw Exception("I is odd");
cout << "Leaving f\n";
}
void testExceptions( int value )
{
cout << "Entering testExceptions\n";
f( value );
cout << "Leaving testExceptions\n";
}
int main()
{
for (int i=0; i<10; i++ )
try
{
cout << "going to call testExceptions\n";
testExceptions( i );
cout << "back from call to testExceptions\n";
}
catch ( Exception e )
{
cout << e.message << endl;
}
}
Exception Example Output
going to call testExceptions
Entering testExceptions
Entering f
I is even
going to call testExceptions
Entering testExceptions
Entering f
I is odd
going to call testExceptions
Entering testExceptions
Entering f
I is even
going to call testExceptions
Entering testExceptions
Entering f
I is odd