C++ - SPLessons

Exception Handling in C++

Chapter 29

SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

Exception Handling in C++

Exception Handling in C++

shape Introduction

When a line of code executes, it might not work sometimes.Errors and failures occurring can be counted throughout the application. In fact, a large part of programming is reacting to that. But some of them are more predictable than others. If users are asked for values, an assumption has to be made at some point that every single user will do some or the other mistake. They might leave something blank that they’re not suppose to leave blank. They might enter a letter where they are supposed to enter a number, those sorts of things.

There are other kinds of errors that are much less predictable, and it’s arguable that testing for them constantly would put a performance hit on the application. So every time, when another piece of memory is allocated from the free store, memory has to be checked whether it is available or not.

Most of the time, checking these sorts of errors every single time is an actively bad thing to do which takes time and slows the application performance, and these things are really unusual, really kind of unexpected. And so that leads to a best practice that says different kinds of errors should be handled in different ways.

The best advantage in C++ when compared to C language is Exception handling. Basically, there are few errors which cannot be detected by the compiler. They are:

As these errors are not identified by the compiler, they are termed as “Exceptions“. Exceptions occurs during the time of execution of the program.

  • Errors occur at “run time” and “compile time” but,  Exceptions occurs mostly at “run-time“.
  • Developer should detect the exception. Errors can be handled by the compiler.

Every time an error occurs, it is not possible to rectify them which will slow down the application performance. To overcome the problem, exceptions are used. Exceptions are nothing but the expected errors which are tested and found solutions before the program gets executed.

shape Description

Exceptions are not the only way to handle errors, especially for expected errors. The best thing to do is to just test them. If the amount to be withdrawn is greater than the amount available for withdrawing, put up an error message, tell the user what they have done wrong right exactly where the problem is found. But the problem is that in some designs, some architectures, the code that actually finds the problem is a really long way away from anywhere that it can tell the user about the problem.

This is the real strength of exceptions. With Exception Handling in CPP, code can be written a lot cleaner with no checking of intermediate return values along the way between a place that can deal with a problem and a place where it might happen. When this very bad unexpected thing happens, it can be said that the exception is thrown.

Exception Handling in CPP can be done using three main blocks.

To know what exception occurred in a program, what() function can be used. For example, e.what() displays the exception occurred.

shape Conceptual
figure

shape Syntax

try
{
// protected code
}
catch( Exceptiontype  e )
{
// alternative statements
}

shape Example

#include <iostream>
using namespace std;
 
int main()
{
   int i = -1;
   cout << "Before try \n";

   try 
   {
      cout << "Yes,exception occured "<< endl;
      if (i < 0)
      {
         throw i;
         cout << "After throwing exception (Never executed)" << endl;
      }
   }
   catch (int i ) 
   {
      cout << "Exception is caught" << endl;
   }
 
cout << "After catch block, you are back " << endl;
return 0;
}

Output

Before try
Yes,exception occured
Exception is caught
After catch block, you are back

shape More Info

Multiple catch blocks are allowed in a program if try block results in one or more exceptions. All these can be handled using a single “catch all” block. It can be represented as catch(...).

shape Example

#include <iostream>
using namespace std;
 
int main()
{
    try  
    {
       throw 5;
    }
    catch (char* exception)  
    {
        cout << "Caught exception " << exception;
    }
    catch (...)  //handles any exception occured
    {
        cout << "Sorry,exception occured.But you are escaped!!!\n";
    }
    return 0;
}

Output

Sorry,exception occured.But you are escaped!!!

Throwing an Exception

shape Description

Instead of using try catch block, Exception Handling in CPP can be done using throw keyword. The type for this expression can be determined by the operands involved in the exception code. The result obtained from the expression used will give the type of exception.

Eg:

int division(int x, int y)
{
if(y == 0 )
{
throw “Division by zero is not valid”;
}
return (x/y);
}

shape Example

#include <iostream>
using namespace std;

int div(int x, int y)
{
   if( y == 0 )
   {
      throw "Division by zero is not allowed";
   }
   return (x/y);
}

int main ()
{
   int a = 5;
   int b = 0;
   int c = 0;
 
   try 
   {
     c = div(a, b);
     cout << c << endl;
   }
   catch (const char* error) 
   {
     cerr << error << endl;
   }
   return 0;
}

Output

Division by zero is not allowed

Built-in Exceptions

shape Description

C++ provides good number of built-in exceptions. The parent class for all the exception classes is exception. This class can handle any exception occurred in the program.

shape Exceptions

shape Table

Description for exceptions derived directly from exception class.

Exceptions Description
bad_alloc Occurs when failure in memory allocation
bad_cast Occurs when dynamic_cast is used incorrect
bad_typeid Exception thrown by typeid function
bad_function_call Exception thrown when an empty function is called
bad_weak_ptr Exception thrown by share_ptr
ios_base::failure Super class for all the stream exceptions
logic_error Super class for some logic error exceptions
runtime_error Super class for some runtime error exceptions
bad_exception It handles unexpected exceptions in C++

shape Example

One can even override the functionality of existing exceptions and create own exceptions.

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

struct OwnException : public exception
{
  const char* what () const throw ()
  {
    return "New exception";
  }
};
 
int main()
{
  try
  {
    throw OwnException();
  }
  catch(OwnException& e)
  {
    cout << "Exception is caught" << std::endl;
    cout << e.what() << std::endl;
  }
  catch(exception& e)
  {
    //any otther exceptions
  }
}

Output

Exception is caught
New exception

Summary

shape Key Points

The chapter Exception Handling in CPP draws out following important points.

  • Errors stops the flow of program.
  • try, throw and catch are performed for Exception Handling in CPP.