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);               f.setSize( 400 , 400 );               f.setLayout( null );               f.setVisible( true );   }   public   static   void  main(String args[]){           new  ScrollbarExample();   }   }   Output: Java AWT Scrollbar Example with AdjustmentListener import  java.awt.*;   import  java.awt.event.*;   class  ScrollbarExample{        ScrollbarExample(){               Frame f=  new  Frame( "Scro

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

C++ this Pointer, static, struct and Enumeration

C++ this Pointer In C++ programming,  this  is a keyword that refers to the current instance of the class. There can be 3 main usage of this keyword in C++. It can be used  to pass current object as a parameter to another method. It can be used  to refer current class instance variable. It can be used  to declare indexers. C++ this Pointer Example Let's see the example of this keyword in C++ that refers to the fields of current class. #include <iostream>    using   namespace  std;   class  Employee {       public :           int  id;  //data member (also instance variable)               string name;  //data member(also instance variable)            float  salary;          Employee( int  id, string name,  float  salary)             {                   this ->id = id;                  this ->name = name;                  this ->salary = salary;            }             void  display()             {                 cout<<id<< "  " <<name<&