Title: 159.234 Lecture 15
1159.234 Lecture 15
Today Revision of arrays and
pointers Exceptions Bibliography Textbook
p309-321 See programs\p25
2- include ltiostreamgt
- include ltassert.hgt
- using namespace std
- // function to print outr an array
- void printArray( int a, int s )
- for(int i 0iltsi)
- cout ltlt ai ltlt " "
-
- cout ltlt endl
-
- // function to allocate memory for an int
array and and initialise to zero - int gimmeAnArray( int s )
- int retval
- retval new ints // memory will be on
teh heap and will outlive the call to - assert( s ! 0 ) // the function
gimmeAnArray - for( int j0jltsj) retvalj 0
- return retval
- for(ptr array1 ptr lt array19 ptr)
// a non-recommended way! - ptr 99 // (the operatror knows how
much to increment int pointers) - cout ltlt "ptr is now " ltlt ptr ltlt endl
-
- printArray( array1, 10 )
- ptr gimmeAnArray( 12 ) // returns a
pointer value to heap memory - printArray( ptr, 12 )
- printArray( array1, 10 )
- delete ptr // the system will probably
take care of this operation - // since it at is the end
of main - // array1 will be taken care of for sure as it
is solely stack based - return 0
-
- Example output
3Exceptions
- Exceptions are run-time errors that a program may
detect. - Examples
- Division by 0
- Access to an array outside of its bounds
- Exhaustion of the free store memory
4Exceptions
Rather than handling errors with assert - which
just stops the program, or exit which also
just stops the program, we can handle errors
using the keywords try, catch and throw
5Using throw
We use throw to indicate an error //divide 43 by
a number entered from keyboard int main() cout
ltlt "Enter an integer " int d cin gtgt d
//stop the program if the entered value is 0 if
(d0) throw // throws a default exception
cout ltlt (43/d)ltlt endl In this example the
thrown exception is caught by the Operating
System so it is effectively the same as an
abort - it just stops the program.
6Throwing an exception
- When the programmer does not specify an
alternative action for the program to take in
case an exception (error) occurs then - the terminate() function is invoked
- this calls abort() which stops the program.
Recall the behaviour of assert() function.
7 Using try - catch
try if (d0) throw "division by
0" cout ltlt (43/d)ltlt endl catch (const
char s) // handle exceptions cout ltlt s
coutltlt1 used for dividend instead" coutltlt"
result "ltlt(43/1)
8Handling exceptions
- The try block -- the part of the program we want
to monitor for errors. - If an exception occurs, it is thrown using throw.
- The exception is caught--using catch, and
processed. - Once an exception has been thrown,
- control passes to the catch expression and
- try block is terminated.
- We sometimes describe the catch clause as a
handler
9How exceptions are handled by catch clauses
More than one catch can be associated with a try
gt different type of exceptions can be caught.
10How exceptions are handled by catch clauses
void Xhandler(int test) try if (test) throw
test else throw Value is zero catch
(int i) cout ltlt Caught One! cout
ltltValueltlti ltlt endl catch (const char
str) cout ltlt Caught a string cout ltlt
str ltlt endl
11How exceptions are handled by catch clauses
int main() cout ltlt "start\n" Xhandler(25) X
handler(0) Xhandler(1) cout ltltend
12The order of execution of catch clauses
IntVectIntVect(int n100) size(n) if
(nlt0) throw(n) p new intsize if(p
0) throw(No memory)
13The order of execution of catch clauses
int IntVectoperator(int i) if ((i lt
0)(i gt size))throw(i) return pi
14 void g(int n) try IntVect a(n)
//... catch(int j) //do something
catch(const char error) //do
something catch(...) //do something
Â
The order of execution of catch clauses
15The order of execution of catch clauses
catch(...) is the syntax for catching
everything. Â The catch handlers have to be
listed in an order that means they can all be
called. Â so catch(...) must be at the end of the
list.
16The order of execution of catch clauses
If a catch doesnt manage to handle the error
completely - then it may re-throw the
exception catch(int j) if (j lt 3)
return//to end of //try block else
throw // pass error up
//to next //enclosing block. The
system catches all exceptions not handled by us,
with the function terminate - which aborts the
program.
17Exception specifications
We can restrict the type of exceptions that a
function can throw.
// This function can only throw ints, chars, //
and doubles. void Xhandler(int test) throw(int,
char, double) if(test 0) throw test
if(test 1) throw 'a' if(test 2) throw
123.23
18Exception specifications
int main() try Xhandler(0) catch(int i)
cout ltlt "Caught int\n" catch(char c)
cout ltlt "Caught char\n" catch(double d)
cout ltlt"Caught double\n"
19- include ltiostreamgt
- include ltexceptiongt
- include ltfstreamgt
- using namespace std
- namespace MyLibrary
- int OPENFAILURE 1
- int OUTOFMEMORY 2
- int CORRUPTFILE 3
- char EmptyFile "Warning Empty File"
- char readHeader( char filename )throw(int,
char) - char temp NULL
- ifstream ifs( filename )
- if ( !ifs )throw OPENFAILURE
- const int bufferSize 1024
- using namespace MyLibrary
- int main()
- char filename80
- cout ltlt "Enter a filename "
- cin.getline( filename, sizeof(filename) )
- char header
- try
- header readHeader( filename )
-
- catch( int ex )
- cout ltlt "Caught exception code " ltlt ex ltlt
endl - exit(1) // could decide here to ask again
if file name was wrong -
- catch( char ex )
- cout ltlt "Caught exception message " ltlt ex ltlt
endl - exit(1)
-
- cout ltlt "Header is" ltlt header ltlt endl
- return 0
20- Design considerations
- Not every C program should use exception
handling. - Throwing exceptions is slower than function
calls. - Use other error handling techniques
- ( such as returning an error code) when
appropriate. - Exception handling is used to communicate program
anomalies between parts of a program that are
developed independently (e.g libraries). - Deciding what should be handled as an exception
is a difficult part of a library design. - It does allow the user of the library to decide
what to do when an error occurs rather than hard
coding the decisions into the library.
21Summary
Exception are run-time error conditions. Normally,
these conditions terminate the user program with
system-provided error message. C code can raise
an exception by using the throw expression. The
exception is handled by invoking an appropriate
handler selected from a list of handlers found at
the end of the handlers try block.
Next Inheritance