Monday, 25 February 2019

Exception Handling in C++ : try catch throw

                    In this post, we will see "Exception Handling in C++" using try, catch, throw.



What is Exception?
Exception is a run time error.

Why is it necessary to handle exceptions?
At run time, we may get unexpected output based on the input we give. Many times, for run time errors, compiler gives the standard error statements as output.
                   Check following program:


Program (exception.cpp)

#include <iostream>

using namespace std;
int main()
{
    int a,b,c;
    cout<<"Enter values for a and b\n";
    cin>>a>>b;
    c=a/b;
    cout<<"Result="<<c<<"\n";
    return 0;
}
  
output (exception.cpp)

parag@parag-Inspiron-N4010:~/Desktop/programs$ g++ exception.cpp
parag@parag-Inspiron-N4010:~/Desktop/programs$ ./a.out
Enter values for a and b
3 0
Floating point exception (core dumped)

             This program is about dividing a number by another number. This program code doesn't have compiler errors. But at time, when we take 3 and 0, it gives error "Floating point exception (core dumped)" as we cannot divide any number by 0. If it is a big code, then it becomes difficult to identify exact errors in the code from the standard error statements. So, it is better; if we give our own error statements. This is possible by using try, catch blocks and throw keyword.

try:  try specifies a block of code in which we may get exception.

throw: throw keyword throws an exception. It transfers control to the catch block.

catch: In catch block, an exception is handled. We may give our own error statement in this block.

              Check the following example. Above same program is written using try, catch, throw keywords.  


Program (exception1.cpp)

#include <iostream>
using namespace std;
int main()
{
    int a, b, c;

    cout<<"Enter values for a and b\n";
    cin>>a>>b;

    /* try block defines a block where we can get exception*/
    try
    {
        if(b == 0)
        {
            // throw exception to catch block
            throw "Division by zero not possible\n";
        }

       c = a/b;
       cout<<"Result="<<c<<"\n";
    }
  
    catch(char const* ex) /* catches and handle exception*/
    {
        cout<<ex;
    }
  
    return 0;
}
  
output (exception1.cpp)

parag@parag-Inspiron-N4010:~/Desktop/programs$ g++ exception1.cpp
parag@parag-Inspiron-N4010:~/Desktop/programs$ ./a.out
Enter values for a and b
3 0
Division by zero not possible
 
                 Hope, you understood the Exception Handling in C++. 
                 Thank you. 

No comments:

Post a Comment