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

JAVA Scrollbar, MenuItem and Menu, PopupMenu

ava AWT Scrollbar The  object  of Scrollbar class is used to add horizontal and vertical scrollbar. Scrollbar is a  GUI  component allows us to see invisible number of rows and columns. AWT Scrollbar class declaration public   class  Scrollbar  extends  Component  implements  Adjustable, Accessible   Java AWT Scrollbar Example import  java.awt.*;   class  ScrollbarExample{   ScrollbarExample(){               Frame f=  new  Frame( "Scrollbar Example" );               Scrollbar s= new  Scrollbar();               s.setBounds( 100 , 100 ,  50 , 100 );               f.add(s);   ...

Difference between net platform and dot net framework...

Difference between net platform and dot net framework... .net platform supports programming languages that are .net compatible. It is the platform using which we can build and develop the applications. .net framework is the engine inside the .net platform which actually compiles and produces the executable code. .net framework contains CLR(Common Language Runtime) and FCL(Framework Class Library) using which it produces the platform independent codes. What is the .NET Framework? The Microsoft .NET Framework is a platform for building, deploying, and running Web Services and applications. It provides a highly productive, standards-based, multi-language environment for integrating existing investments with next-generation applications and services as well as the agility to solve the challenges of deployment and operation of Internet-scale applications. The .NET Framework consists of three main parts: the common language runtime, a hierarchical set of unified class librari...

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