Skip to main content

C++ Exception Handling

C++ Exception Handling

Exception Handling in C++ is a process to handle runtime errors. We perform exception handling so the normal flow of the application can be maintained even after runtime errors.

In C++, exception is an event or object which is thrown at runtime. All exceptions are derived from std::exception class. It is a runtime error which can be handled. If we don't handle the exception, it prints exception message and terminates the program.


Advantage

It maintains the normal flow of the application. In such case, rest of the code is executed even after exception.


C++ Exception Classes

In C++ standard exceptions are defined in <exception> class that we can use inside our programs. The arrangement of parent-child class hierarchy is shown below:

Cpp Exception handling 1

All the exception classes in C++ are derived from std::exception class. Let's see the list of C++ common exception classes.

ExceptionDescription
std::exceptionIt is an exception and parent class of all standard C++ exceptions.
std::logic_failureIt is an exception that can be detected by reading a code.
std::runtime_errorIt is an exception that cannot be detected by reading a code.
std::bad_exceptionIt is used to handle the unexpected exceptions in a c++ program.
std::bad_castThis exception is generally be thrown by dynamic_cast.
std::bad_typeidThis exception is generally be thrown by typeid.
std::bad_allocThis exception is generally be thrown by new.

C++ Exception Handling Keywords

In C++, we use 3 keywords to perform exception handling:

  • try
  • catch, and
  • throw

C++ try/catch

In C++ programming, exception handling is performed using try/catch statement. The C++ try block is used to place the code that may occur exception. The catch block is used to handle the exception.


C++ example without try/catch

  1. #include <iostream>  
  2. using namespace std;  
  3. float division(int x, int y) {  
  4.    return (x/y);  
  5. }  
  6. int main () {  
  7.    int i = 50;  
  8.    int j = 0;  
  9.    float k = 0;  
  10.       k = division(i, j);  
  11.       cout << k << endl;  
  12.    return 0;  
  13. }  

Output:

Floating point exception (core dumped)  

C++ try/catch example

  1. #include <iostream>  
  2. using namespace std;  
  3. float division(int x, int y) {  
  4.    if( y == 0 ) {  
  5.       throw "Attempted to divide by zero!";  
  6.    }  
  7.    return (x/y);  
  8. }  
  9. int main () {  
  10.    int i = 25;  
  11.    int j = 0;  
  12.    float k = 0;  
  13.    try {  
  14.       k = division(i, j);  
  15.       cout << k << endl;  
  16.    }catch (const char* e) {  
  17.       cerr << e << endl;  
  18.    }  
  19.    return 0;  
  20. }  

Output:

Attempted to divide by zero!


C++ User-Defined Exceptions

The new exception can be defined by overriding and inheriting exception class functionality.

C++ user-defined exception example

Let's see the simple example of user-defined exception in which std::exception class is used to define the exception.

  1. #include <iostream>  
  2. #include <exception>  
  3. using namespace std;  
  4. class MyException : public exception{  
  5.     public:  
  6.         const char * what() const throw()  
  7.         {  
  8.             return "Attempted to divide by zero!\n";  
  9.         }  
  10. };  
  11. int main()  
  12. {  
  13.     try  
  14.     {  
  15.         int x, y;  
  16.         cout << "Enter the two numbers : \n";  
  17.         cin >> x >> y;  
  18.         if (y == 0)  
  19.         {  
  20.             MyException z;  
  21.             throw z;  
  22.         }  
  23.         else  
  24.         {  
  25.             cout << "x / y = " << x/y << endl;  
  26.         }  
  27.     }  
  28.     catch(exception& e)  
  29.     {  
  30.         cout << e.what();  
  31.     }  
  32. }  

Output:

Enter the two numbers :
10
2
x / y = 5  

Output:

Enter the two numbers :
10
0
Attempted to divide by zero!



Anurag Rana

Comments

Popular posts from this blog

Standard and Formatted Input / Output in C++

The C++ standard libraries provide an extensive set of input/output capabilities which we will see in subsequent chapters. This chapter will discuss very basic and most common I/O operations required for C++ programming. C++ I/O occurs in streams, which are sequences of bytes. If bytes flow from a device like a keyboard, a disk drive, or a network connection etc. to main memory, this is called   input operation   and if bytes flow from main memory to a device like a display screen, a printer, a disk drive, or a network connection, etc., this is called   output operation . Standard Input and Output in C++ is done through the use of  streams . Streams are generic places to send or receive data. In C++, I/O is done through classes and objects defined in the header file  <iostream> .  iostream  stands for standard input-output stream. This header file contains definitions to objects like  cin ,  cout , etc. /O Library Header Files There are...

Genetic Algorithm: Population, Fitness Function, Parent Selection, Cross over, Mutation

Genetic Algo Population Population is a subset of solutions in the current generation. It can also be defined as a set of chromosomes. There are several things to be kept in mind when dealing with GA population − The diversity of the population should be maintained otherwise it might lead to premature convergence. The population size should not be kept very large as it can cause a GA to slow down, while a smaller population might not be enough for a good mating pool. Therefore, an optimal population size needs to be decided by trial and error. The population is usually defined as a two dimensional array of –  size population, size x, chromosome size . Population Initialization There are two primary methods to initialize a population in a GA. They are − Random Initialization  − Populate the initial population with completely random solutions. Heuristic initialization  − Populate the initial population using a known heuristic for the problem. It has been observed that the e...

C++ (Object and Class)

The major purpose of C++ programming is to introduce the concept of object orientation to the C programming language. Object Oriented Programming is a paradigm that provides many concepts such as  inheritance, data binding, polymorphism etc. The programming paradigm where everything is represented as an object is known as truly object-oriented programming language.  Smalltalk  is considered as the first truly object-oriented programming language. OOPs (Object Oriented Programming System) Object  means a real word entity such as pen, chair, table etc.  Object-Oriented Programming  is a methodology or paradigm to design a program using classes and objects. It simplifies the software development and maintenance by providing some concepts: Object Class Inheritance Polymorphism Abstraction Encapsulation C++ Object In C++, Object is a real world entity, for example, chair, car, pen, mobile, laptop etc. In other words, object is an ent...