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

Standard Exceptions


C++ provides standard exceptions that can be used to catch exceptions thrown by the language.


File: mem1.cpp
#include <iostream>
#include <exception>
using namespace std;

// bad_alloc standard exception

int main ()
{
  try
   {
     int* myarray ;
     while( 1 )
       myarray = new int[100000000];
   }
   catch (exception& e)
   {
      cout << "Standard exception: " << e.what() << endl;
   }
   return 0;
}
$ g++ mem1.cpp ; ./a.exe
Standard exception: std::bad_alloc

We can also derive our own class from the exception class.


File: mem2.cpp
// using standard exceptions

#include <iostream>
#include <exception>
using namespace std;

class myexception: public exception
{
  virtual const char* what() const throw()
  {
     return "My exception happened";
  }
} ;

int main ()
{
    try
     {
         myexception myex ;
         throw myex;
     }
    catch (exception& e)
    {
        cout << e.what() << '\n';
    }
    return 0;
}
Exception specifications allow us to specify if a method throws an exception or not. In the below code the "method3" is called but the exception is not caught even though there is a try catch block. This is because the "method3" threw an exception even though we declared that it does not do so.


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

using namespace std;

//Old style before c++ 11
void method1() throw()
{

}

//Recommended style after c++ 11
//It means the method2 does not throw
//an exception
void method2() noexcept
{

}
//This means the method3 does not throw
//an exception.
void method3()  throw()
{
   throw 5 ;
}


int main()
{
   try
    {
       method3() ;
    }
   catch ( int& err )
    {
        cout << "Inside catch." << endl ;
    }

  return 0;
}