Pages

Monday 6 September 2021

Exception Handling in C++

C++ Exceptions
When executing C++ code, different errors can occur: 
  • coding errors made by the programmer
  • errors due to wrong input.
  • The technical term for this is: C++ will throw an exception (throw an error).
C++ try throw and catch
It consist of three keywords: try, throw and catch:

The try statement allows you to define a block of code to be tested for errors while it is being executed.

The throw keyword throws an exception when a problem is detected, 

The catch statement allows you to define a block of code to be executed, if an error occurs in the try block.

The try, throw and catch keywords can not run in Turboc++ it can run on other software's available such as Dev c++

#include<iostream>
using namespace std;
int main()
 {
   int a,b;
   try
    {
     cout<<"enter a and b value:";
     cin>>a>>b;
     if (b == 0)
        throw (0);
     else
cout << "division is :"<<a/b;
    }
   catch (int x)
    {
    cout << "Division not possible ";
    }
  return 0;
}

No comments:

Post a Comment

Constructors & Destructors in c++

  Constructors :  A Constructor is a special member function, which is used to initialize the objects of its class. The Constructor is invok...