Search Contact information
University of Cambridge Home Department of Engineering
UniversityM- ofM- Cambridge >  Engineering Department >  computing help >  Languages >  C++

Exceptions

Suppose you have a low-level routine called routine4 which might need to communicate an error message to a top-level routine called routine1. routine1 doesn't call routine4 directly but via routine2 and routine3. The traditional way to determine the success or otherwise of a routine is to check the value that it returns, but in this case that means making the value pass through routine2 and routine3 (see the example on the left) which complicates the code. The example on the right shows how using exceptions can make the intermediate routines simpler.

Using error codesUsing exceptions
#define OK 1 try{
int routine4(){ void routine4(){
int return_value;std:exception e;
// Do something. If it goes wrong, // Do something. If it goes wrong,
// tell routine1 by setting // tell routine1 by throwing a message
// return_value accordingly
   return return_value ;    throw(e);
}}
 
int routine3(){ void routine3(){
int return_value;
   return_value=routine4();   routine4();
   if (return_value != OK)
      return return_value;
   ......
} }
 
int routine2(){ void routine2(){
int return_value;
   return_value=routine3();    routine3();
   if (return_value != OK)
      return return_value;
   ......
} }
 
int routine1(){ void routine1(){
int return_value;
   return_value=routine2();    routine2();
   if (return_value != OK)
      // try to recover
}}
} // end of the try
 
catch(std:exception& e){
       // try to recover
}
© Cambridge University Engineering Dept
Information provided by Tim Love (tpl)
Last updated: February 2000