Exception Handling in CPP

  • By Shubham Baghel
  • May 21, 2021
  • C & C++

Exception :-

It is an event, that occurres when we running program, which disturbs entire CPP program, to avoid this scenarios we use Exception Handling (When we this mechanism we can able to maintain normal flow of program execution). An exception is a problem that occurres during the execution of a program at runtime. A CPP exception is response to an exceptional situation that arises while a program is executing, for example trying to divide any number by zero, this is undefined condition.

In CPP Exceptions Classes will provides a way to transfer control from one part of a program to another part. To Handle CPP runtime exceptions we use these three main keywords, those are try, catch, and throw.

throw: When we are executing any CPP program that throws an exception when a problem arises in the program. This scenario is done by using a keyword called throw.

For Free, Demo classes Call: 8149467521
Registration Link: Click Here!

 

catch: A CPP program catches an exception with the help of an exception handler at the place in a CPP program, where we want to handle the problem. With the help of catch keyword indicates the catching of an exceptions.

try: try block verifies a block of code of the CPP program for which particular exceptions will be activated. followed by block we can have one or more catch blocks in a program.

Assume that a block will raise an exception, a particular method catches an exception using a combination of both the try and catch blocks. A try/catch block is placed around the code that may generate an exception. The code within a try/catch blocks is referred to as protected code.

The syntax try/catch:

try 

{

   //problematic code

   //Only problematic code will goes here

catch(Exception-Name e1) 

{

   //catch block

   //Alternate code for try block code will goes here

catch(Exception-Name e2) 

{

   //catch block

   //Alternate code for try block code will goes here

catch(Exception-Name en) 

{

   //catch block

   //Alternate code for try block code will goes here

We can list out multiple catch blocks to catch different types of exception statements in case of try block raises multiple exceptions in different scenarios.

For Free, Demo classes Call: 8149467521
Registration Link: Click Here!

Throwing Exceptions in CPP:

The CPP Exceptions could be thrown anywhere within a code block using throw keyword. The operands of the throw keyword finds a type of the exception and could be any statement and the type of the result of the statement determines the type of exceptions thrown in a program.

Example:-

#include <iostream>

using namespace std;

 

//function declaration 

int division(int a, int b);

 

//function implementation 

int division(int a, int b) 

{

    if(b == 0)

{

       throw “Division by zero condition!”;

    }

   

    return (a/b);

}

 

int main() 

{

int division;

//calling function

division = division(200, 0)

cout<<“Division: “<<division<<endl;

 

return 0;

}

 

For Free, Demo classes Call: 8149467521
Registration Link: Click Here!

 

Catching Exceptions in CPP:

In CPP, the catch block following the try block catches any type of exceptions. We can specify what type of exception we want to catch and this is determined by the exception declarations that appears in parentheses().

try 

{

   // protected code

   // problematic code goes here.

 

 

catch(Exception-Name e) 

{

  // code to handle Exception-Name exception here

  // Handler part goes here

}

From the above code will catch an exception of Exception-Name type. 

Suppose, If we want to specify that a catch block should handle any type of exceptions then that is thrown in a try block, we must put an ellipsis(…), between the parentheses enclosing the exception declarations.

try 

{

   // protected code

   // problematic code goes here.

   

catch(…) 

{

  // code to handle any exception

  // Handler part goes here

}

The following CPP program is an example, which throws a divide by zero exception and followed catch block it in catch block.

 

#include <iostream>

using namespace std;

 

//function declaration

int division(int num1, int num1);

 

//function implementation

int division(int num1, int num1) 

{

    if(num2 == 0) 

{

       throw “Divide by zero!”;

    }

    return (num1/num2);

}

For Free, Demo classes Call: 8149467521
Registration Link: Click Here!

 

int main () 

{

   int a1 = 50;

   int b1 = 0;

   int result = 0;

   cout<<“Enter first value: “<<endl;

   cin>>a1;

   cout<<“Enter second value: “<<endl;

   cin>>b1; 

   try 

   {

      result = division(a1, b1);

      cout << result << endl;

   } 

   catch(const char* exception1) 

   {

      cerr <<exception1<<endl;

   }

 

   return 0;

}

 

From the above program we understand that there is raising the type of an exception const char*. The output of the above code is,

Divide by zero!

Standard Exceptions in CPP:

The CPP language provides a list of standard exceptions defined in <exception> library which can help to do exception handling in our programs.

Sr.No Exceptions and Description
1 std::exception

An exception class is super or parent or base class of all the standard CPP exception classes.

2 std::bad_alloc

This exception could be thrown by new keyword.

3 std::bad_cast

This given exception can thrown by dynamic_cast keyword.

4 std::bad_exception

This is exception is useful when system to handle unexpected exception class in a CPP program.

5 std::bad_typeid

This given exception can be thrown by typeid keyword statement.

6 std::logic_error

This kind of an exception is occurs because of theoretical statements, that can be detected by reading the code from externally.

7 std::domain_error

This is an exception class thrown when a mathematical related expressions are  used in invalid domain.

8 std::invalid_argument

This kind of exception is thrown because of invalid arguments.

9 std::length_error

This exception statement is thrown when a too big std::string data is created.

10 std::out_of_range

This exception statement could thrown by the ‘at’ method, let us take an example a std::vector and std::bitset<>::operator[]() scenarios.

11 std::runtime_error

This type of an exception thrown that theoretically cannot be detected by reading the CPP program code.

12 std::overflow_error

This kind of error is thrown because of mathematical overflow statements.

 

 

How to define custom Exceptions in CPP:

In CPP language we can define our own exceptions by inheriting exception class and its functionality. The following is the example, which shows how we can use std::exception class to implement our own custom exception.

 

#include <iostream>

#include <exception>

using namespace std;

 

struct CustomException: public exception 

{

   const char * what () const throw () 

   {

       return “CPP Exceptions”;

   }

 

};

 

int main() 

{

   try 

   {

      throw CustomException();

   } 

   catch(CustomException& e) 

   {

      std::cout <<CustomException caught”<< std::endl;

      std::cout<<e.what()<<std::endl;

   } 

 

For Free, Demo classes Call: 8149467521
Registration Link: Click Here!

 

   catch(std::exception& e) 

   {

      //Other exceptions

   }

}

 

From the above Here, what() is a public method it is part exception class and it has been overridden by all the derived exception classes.

 

 

Author:- Patil,Namdev

Call the Trainer and Book your free demo class for now!!!

© Copyright 2020 | Sevenmentor Pvt Ltd.

 

Submit Comment

Your email address will not be published. Required fields are marked *

*
*