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

Inheritance

If we have a hierarchy then we can throw a derived exception and catch it with the base class.

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

using namespace std;

class MyExceptionBase 
{    
  public: 
   string messg ; 
   MyExceptionBase( string str1 ) 
    {     
       messg = str1 ; 
     }
};

class MyException : public MyExceptionBase
{ 
  public: 
    MyException( string str1 ) : MyExceptionBase( str1 )
    {
    }
};

int main()
{  
    try
      { 
        throw MyException("Error") ; 
      } 
    catch ( MyExceptionBase& e1 )
      { 
         cout << e1.messg   << endl ; 
      } 
     return 0;
}
$ g++ except8.cpp ; ./a.exe
Error
If we list the classes in a hierarchy we need to make sure we list the derived classes first. The logic is that otherwise the base class catch will catch all the exceptions. We want to catch the specifice exceptions first.
The following produces a warning.

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

using namespace std;

class MyExceptionBase
{
  public:
   string messg ;
   MyExceptionBase( string str1 )
    {
       messg = str1 ;
     }
};

class MyException : public MyExceptionBase
{
  public:
    MyException( string str1 ) : MyExceptionBase( str1 )
    {
    }
};

int main()
{
    try
      {
        throw MyException("Error") ;
      }

    catch ( MyExceptionBase& e1 )
      {
         cout << e1.messg   << endl ;
      }

    catch ( MyException& e1 )
      {
         cout << "Derived" << e1.messg   << endl ;
      }
     return 0;
}
$ g++ except9.cpp ; ./a.exe
except9.cpp: In function �int main()�:
except9.cpp:36:5: warning: exception of type �MyException� will be caught by earlier handler [-Wexceptions]
   36 |     catch ( MyException& e1 )
      |     ^~~~~
except9.cpp:31:5: note: for type �MyExceptionBase�
   31 |     catch ( MyExceptionBase& e1 )
      |     ^~~~~
Error
It should be written as:

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

using namespace std;

class MyExceptionBase
{
  public:
   string messg ;
   MyExceptionBase( string str1 )
    {
       messg = str1 ;
     }
};

class MyException : public MyExceptionBase
{
  public:
    MyException( string str1 ) : MyExceptionBase( str1 )
    {
    }
};

int main()
{
    try
      {
        throw MyException("Error") ;
      }


    catch ( MyException& e1 )
      {
         cout << e1.messg   << endl ;
      }

    catch ( MyExceptionBase& e1 )
       {
          cout << e1.messg   << endl ;
       }

  return 0;
}
$ g++ except10.cpp ; ./a.exe
Error