Exception handling in C++

Aug 11, 2019

Exception

Exceptions are the errors that occur at the run time of a program. The errors may be any unusual/unwanted occurrence such as running out of memory, not being able to open a file, divide by zero, and so forth. They can be categorized into two types.

  1. Synchronous Exception-- Exceptions that occur due to problems in input data or inappropriate ways of handling data are Synchronous exceptions. For example index out of range, overflow, underflow, not being able to open a file, I/O error, etc.
  2. Asynchronous Exception-- Exceptions that are caused by events or faults unrelated to the program, external agents are called asynchronous exceptions. Keyboard interrupt, hardware malfunction, disk failure, etc. are examples of asynchronous exceptions.

Exception Handling

Detection of unusual/unwanted behavior of the program in run-time and taking preventive measures is called exception handling. Exception handling mechanism attempts to build fault-tolerant system. It tries to increase reliability by designing the system that continues to provide the service in spite of the presence of the faults. Exception handling provides a way to transfer control from one part of a program to another.

Steps in exception handling:

  1. Hit the exception
  2. Throw the exception
  3. Catch the exception
  4. Handle the exception

Exception handling in C++ is built upon three blocks/keywords: try, catch and block.

 

try, catch and throw in C++
try, catch and throw in C++

 

I) throw construct:

When the problem is detected during runtime an exception is raised by using the keyword throw. A temporary object of some type is initialized by the throw-expression. And the type of object that is thrown is used in matching catch block. Syntax is:

throw obj;

where the throw is keyword and obj is an object of some type. The part of the code that throws exceptions or from within the function called from that point should be enclosed within the try block if it is to be handled.

 

II) catch construct: 

This is the block, where the raised exceptions are handled. The exception handler is indicated by the keyword catch. It must be used immediately after the try block. There can be multiple catch blocks. Each handler evaluates the exception that matches. The syntax is:

catch (type [arg])

{

    //exception handling code

}

The arg refers to the parameter whose value will be the valueof the object that is thrown during exception.

 

III) try construct:

 This block contains the code, where there is a chance of raising the exception directly from there or from the functions that are called directly or indirectly from there. This block actually monitors the code for probable exception. If the exception is raised, then the program control is transferred to the respective catch block that is matched. The syntax is:

try

{

    //code that raises exception 

    //or function call that raises exception

}

 

Try, catch, throw together

try{

    //codes or functions that 

    //can raise an exception

}

catch(type1 obj1){

    //codes to handle type1 exception

}

catch(type2 obj2){

    //codes to handle type2 exception

}

.

.

.

.

catch(typen objn){

    //code to handle typen exception

}

 

 Example:divide by zero exception.

//example of divide by zero exception
#include <iostream>
using namespace std;

int main(){
    float x, y, z;
    cout<<"Enter value of x and y:";
    cin>>x>>y;
    try{
        if(y == 0){
            //throwing exception with const char *  type
            throw "Divide by zero exception.";
        }
        z = x/y;
        cout<<"Value of x/y = "<<z<<endl;
    }catch(const char * msg){
        cout<<"Exception occured."<<endl;
        cout<<msg<<endl;//printing the exception caught
    }
    return 0;
}

 Sample run:

Enter value of x and y:12.2
0
Exception occured.
Divide by zero exception.

 

Since we are throwing exception of type const char *, we have to specify const char * in the catch block to catch the exception.

 

Catching all the exception:

In C++, there is a provision to catch all exceptions raised in the try block without knowing the type. The syntax is:

catch(...){

    /handling the exception

}

This handler should be kept at the last catch block if multiple catch block follows the try block. If we place this type of catch block at first then none of the catch blocks following this block is executed.

 

C++ standard Exceptions:

C++ provides standard exceptions that are defined in the <exception> library, which we can use directly in our programs. They are placed in parent-child class hierarchy as:

C++ standard exception class hierarchy
C++ standard exception class hierarchy

 

S.N. Exception & Description
1

std::exception

An exception and parent class of all the standard C++ exceptions.

2

std::bad_alloc

This can be thrown by new.

3

std::bad_cast

This can be thrown by dynamic_cast.

4

std::bad_exception

This is useful device to handle unexpected exceptions in a C++ program.

5

std::bad_typeid

This can be thrown by typeid.

6

std::logic_error

An exception that theoretically can be detected by reading the code.

7

std::domain_error

This is an exception thrown when a mathematically invalid domain is used.

8

std::invalid_argument

This is thrown due to invalid arguments.

9

std::length_error

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

10

std::out_of_range

This can be thrown by the 'at' method, for example a std::vector and std::bitset<>::operator[]().

11

std::runtime_error

An exception that theoretically cannot be detected by reading the code.

12

std::overflow_error

This is thrown if a mathematical overflow occurs.

13

std::range_error

This is occurred when you try to store a value which is out of range.

14

std::underflow_error

This is thrown if a mathematical underflow occurs.

Defining new exceptions in c++

New exceptions can be defined by inheriting the standard exception classes.

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

struct MyException : public exception {
   const char * what () const throw () {
      return "C++ Custom Exception";
   }
};

int main() {
   try {
      throw MyException();
   }catch(MyException obj){
    cout<<"Exception caught:"<<endl;
     cout<<obj.what()<<endl;
   }
   catch(...) {
      cout<<"Something wrong"<<endl;
   }
   return 0;
}

sample run:

Exception caught:
C++ Custom Exception

 

Related


Tools/Apps





© Nepal Exchange Rates