Menu

C++ TUTORIALS - C++ Exception Handling

C++ Exception Handling

ADVERTISEMENTS

C++ Standard Exceptions:

ExceptionDescription
std::exceptionAn exception and parent class of all the standard C++ exceptions.
std::bad_allocThis can be thrown by new.
std::bad_castThis can be thrown by dynamic_cast.
std::bad_exceptionThis is useful device to handle unexpected exceptions in a C++ program
std::bad_typeidThis can be thrown by typeid.
std::logic_errorAn exception that theoretically can be detected by reading the code.
std::domain_errorThis is an exception thrown when a mathematically invalid domain is used
std::invalid_argumentThis is thrown due to invalid arguments.
std::length_errorThis is thrown when a too big std::string is created
std::out_of_rangeThis can be thrown by the at method from for example a std::vector and std::bitset<>::operator[]().
std::runtime_errorAn exception that theoretically can not be detected by reading the code.
std::overflow_errorThis is thrown if a mathematical overflow occurs.
std::range_errorThis is occured when you try to store a value which is out of range.
std::underflow_errorThis is thrown if a mathematical underflow occurs.

ADVERTISEMENTS

try
{
   // protected code
}catch( ExceptionName e1 )
{
   // catch block
}catch( ExceptionName e2 )
{
   // catch block
}catch( ExceptionName eN )
{
   // catch block
}

ADVERTISEMENTS

Throwing Exceptions:

double division(int a, int b)
{
   if( b == 0 )
   {
      throw "Division by zero condition!";
   }
   return (a/b);
}

Catching Exceptions:

try
{
   // protected code
}catch( ExceptionName e )
{
  // code to handle ExceptionName exception
}

try
{
   // protected code
}catch(...)
{
  // code to handle any exception
}

#include <iostream>
using namespace std;

double division(int a, int b)
{
   if( b == 0 )
   {
      throw "Division by zero condition!";
   }
   return (a/b);
}

int main ()
{
   int x = 50;
   int y = 0;
   double z = 0;
 
   try {
     z = division(x, y);
     cout << z << endl;
   }catch (const char* msg) {
     cerr << msg << endl;
   }

   return 0;
}

Define New Exceptions:

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

struct MyException : public exception
{
  const char * what () const throw ()
  {
    return "C++ Exception";
  }
};
 
int main()
{
  try
  {
    throw MyException();
  }
  catch(MyException& e)
  {
    std::cout << "MyException caught" << std::endl;
    std::cout << e.what() << std::endl;
  }
  catch(std::exception& e)
  {
    //Other errors
  }
}