Home C++ Introduction Decisions Loops Input/Output Functions Stack and Heap References Arrays Searching and Sorting Recursion Pointers Character and Strings Structures Classes Inheritance Exceptions Templatess STL Modern C++ Misc Books ----


Exceptions


Contents

Multiple Catch


We can also have multiple catch statements corresponding to our try block.

File: except3.cpp
#include <iostream>
#include <fstream>

using namespace std;

int ErrorCode = 0 ;
int divideOperation1
( int x1, int y1 )
{
   ErrorCode = 0 ;
   if ( y1 == 0 )
   {
    ErrorCode = -1 ;
    return 0 ;
   }
   return ( x1 / y1 ) ;
 }

 int divideOperation2( int x1, int y1 )
 {
     ErrorCode = 0 ;
     if ( y1 == 0 )
      {
           throw "Divide by zero." ;
      }
     return ( x1 / y1 ) ;
 }

 int main()
 {
     divideOperation1 ( 4 ,  0 ) ;
     if ( ErrorCode == -1 )
       cout << "Error divisor is zero." << endl ;
       // throw 1 ;
     try
     {
         throw 5 ;
         //throw statement can occur anywhere
         divideOperation2 ( 4 ,  0 ) ;
     }
     catch ( const char* str1 )
     {
         cout << str1  << endl ;
     }
     //Reference to avoid a copy
     catch ( int& e1 )
     {
         cout << "Integer Exception"   << endl ;
         return 1 ;
     }
     return 0;
}
Output:
$ g++ except3.cpp ; ./a.exe
Error divisor is zero.
Integer Exception./a.exe

We have 2 catch statements that correspond to the try block. One is to catch strings and the other
is to catch an integer. The "divideOperation2" with the divisor of zero in this case would have
thrown an exception but we never reach that line because the
"throw 5"
is executed.

Excercise

1) What does the below program print ?
File: multi_ex1.cpp
#include <iostream>
#include <fstream>

using namespace std;

int ErrorCode = 0 ;
int divideOperation1
( int x1, int y1 )
{
   ErrorCode = 0 ;
   if ( y1 == 0 )
   {
    ErrorCode = -1 ;
    return 0 ;
   }
   return ( x1 / y1 ) ;
 }

 int divideOperation2( int x1, int y1 )
 {
     ErrorCode = 0 ;
     if ( y1 == 0 )
      {
           throw "Divide by zero." ;
      }
     return ( x1 / y1 ) ;
 }

 int main()
 {
     divideOperation1 ( 4 ,  0 ) ;
     if ( ErrorCode == -1 )
       cout << "Error divisor is zero." << endl ;

     try
     {
         divideOperation2 ( 4 ,  0 ) ;
     }
     catch ( const char* str1 )
     {
         cout << str1  << endl ;
         throw 5 ;
     }
     //Reference to avoid a copy
     catch ( int& e1 )
     {
         cout << "Integer Exception"   << endl ;
         return 1 ;
     }
     cout << "End of Main."   << endl ;
     return 0;
}