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...

Data Warehousing - An Overview

Anurag Information Technology (IT) has historically influenced organizational performance and competitive standing. The increasing processing power and sophistication of analytical tools and techniques have put the strong foundation for the product called data warehouse. There are a number of reasons that any organization should consider a data warehouse, which can be the critical tool for maximizing the organization’s investment in the information it has collected and stored throughout the enterprise. IT managers need to understand the rationale and benefits of data warehouses because they may need to design and implement, or procure this kingpin of business intelligence. The data warehouses are supposed to provide storage, functionality and responsiveness to queries beyond the capabilities of today's transaction-oriented databases. Also data warehouses are set to improve the data access performance of databases. Traditional databases balance the requirement of data access w...

Genotype Representation

Binary Representation This is one of the simplest and most widely used representation in GAs. In this type of representation the genotype consists of bit strings. For some problems when the solution space consists of Boolean decision variables – yes or no, the binary representation is natural. Take for example the 0/1 Knapsack Problem. If there are n items, we can represent a solution by a binary string of n elements, where the x th  element tells whether the item x is picked (1) or not (0). For other problems, specifically those dealing with numbers, we can represent the numbers with their binary representation. The problem with this kind of encoding is that different bits have different significance and therefore mutation and crossover operators can have undesired consequences. This can be resolved to some extent by using  Gray Coding,  as a change in one bit does not have a massive effect on the solution. Real Valued Representation For problems where we want to define ...