Site icon DataFlair

Exception Handling in C++ | Make it possible by try, catch & throw

Free C++ course with real-time projects Start Now!!

We might encounter certain situations in which the operations that we perform might not be legal, which means that it might be unacceptable mathematically or logically when working with a wide variety of values. This is where the role of exception handling comes into play. Exception handling in C++ helps us to tackle unforeseen situations during programming.

C++ gives us an upper edge over other programming languages that do not support the feature of exception handling, like the C.

It is for sure that, after reading this C++ exception handling tutorial you’ll not find any of the difficulties.

What is Exception Handling in C++?

In C++, an exception is nothing but anomalies or problems that arise during program execution. The concept of exception handling allows us to deal with such problems.

One of the most popular exceptions in C++ is the division of a number by 0. The C++ compiler does not understand that it is an illegal operation to divide a number by zero or to take the square root of a negative number. These are referred to as mathematical exceptions.

Here are some of the keywords associated with exception handling that we need to keep in mind while implementing this concept in our C++ programs:

Exceptions basically help us to figure out ways in which the flow of control of a fragment of code can be transferred from one part of the program to the other.

We need to employ the three major keywords in order to implement a program based on exception handling:

1. try block

The try keyword specifies the particular block of code in which the programmer finds that exception handling needs to be implemented.

2. catch block

The catch keyword indicates that the C++ compiler has caught an exception.

The basic syntax of using the try and catch keywords are:

try
{
// protected code
}
catch( Exception_name e1 )
{
// catch block
} catch( Exception_name e2 )
{
// catch block
}
.
.
catch( Exception_name eN )
{
// catch block
}

There can be as many catch statements as you like while working with the try keyword.

C++ gives us the provision to throw an exception anywhere inside the program with the help of the ‘throw’ keyword.

7 Mind Blowing C++ Application that you Must Know

3. throw statement

The C++ compiler would get an instruction to throw away the exception causing the program to behave anomalously. In simple words, the ‘throw’ keyword throws an exception.

An exception can be caught with the help of a combination of the try and catch keywords.

The basic syntax of throwing an exception in C++ is:

return_type function_name( arguments )
{
if( Exception )
{
throw “Message”;
}
return (Answer for valid condition);
}

Importance of Exception Handling in C++

Before starting any new topic, you must ask yourself- “Why am I here to learn this topic?”

In this tutorial, we will help you answer this question as well as those questions that will help you ponder in depth of this topic. Let us acknowledge the significance of exception handling by considering an example.

Suppose you want to take the input of an array of strings to maintain a record of who all you want to invite for a party. But there are certain people who you do not wish to invite at any cost.

Wait a minute and revise the concept of Strings in C/C++

With the help of exception handling in C++, you would be able to solve this problem if you happen to enter the names of unwanted people at your party accidentally.

To sum it up, here are some of the reasons why we employ the concept of exception handling:

  1. Exception handling helps the programmer to separate the exceptional cases and if-else conditions (the normal code). It helps in enhancing the readability of the code and makes it less prone to any sort of errors or self-defined exceptional conditions.
  2. C++ allows you to throw as many exceptions as you want without necessarily having to deal with the catch statements. It provides flexibility to the code for the programmer.
  3. We can easily group together the same types of errors making our work easy and simple.

Implementation of Exception Handling in C++

Let us consider one of the most popular examples of exception handling in C++:

Division by Zero problem.

This is how it can be handled with the help of exception handling:

#include <iostream>
using namespace std;

int division(int numerator, int denominator) 
{
if( denominator == 0 ) 
{
throw "Division by zero condition!";
}
return (numerator / denominator );
}

int main () 
{

cout<<"Welcome to DataFlair tutorials!"<<endl<<endl;

try 
{
int result = division(20, 0);
cout<<"The dividend of the numbers is: "<<result<<endl;
}
catch (const char* message) 
{
cerr<< message<< endl;
}

return 0;
}

Code-

Output-

Elucidation-

Let us now discuss the main components of the program one by one:

We have created a function to divide an integral value by another. While performing division, it is important to keep in mind that the denominator cannot be zero.

Therefore, we threw the base condition “Divison by zero condition!” if the value of the denominator entered by the user is 0. This was done with the help of the “throw” statement. If the denominator is not equal to zero, then the function would return the value of numerator/denominator.

Moving on towards the “try” statement, we observe that we passed the values of both numerator and denominator in which we entered 0 as the denominator value. Since the division by zero conditions comes into the picture in this case, we use the “catch” statement to return the error message.

To run and execute the above C++ code, Install g++ compiler on Linux

Tips and Tricks while working with Exceptions in C++

After developing an understanding of how to implement exception handling in C++, let us discuss some of the glitches that we need to keep in mind while working with exceptions.

catch (…)

try
{
throw ‘z’;
}
catch ( int number )
{
cout << “Caught ” << number;

In this code segment, the alphabet ‘z’ is not implicitly converted to an integer yielding its ASCII value.

Quiz on Exception Handling in C++

Time limit: 0

Quiz Summary

0 of 15 Questions completed

Questions:

Information

You have already completed the quiz before. Hence you can not start it again.

Quiz is loading…

You must sign in or sign up to start the quiz.

You must first complete the following:

Results

Quiz complete. Results are being recorded.

Results

0 of 15 Questions answered correctly

Your time:

Time has elapsed

You have reached 0 of 0 point(s), (0)

Earned Point(s): 0 of 0, (0)
0 Essay(s) Pending (Possible Point(s): 0)

Categories

  1. Not categorized 0%
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  1. Current
  2. Review / Skip
  3. Answered
  4. Correct
  5. Incorrect
  1. Question 1 of 15
    1. Question

    What will be the output of the following program?

    #include <iostream>

     

    using namespace std;

    int divide(int x, int y)

    {

    int z;

    if(x==0)

    {

         throw”division by 0″;

    }

    else

    {

    z=y/x;

    return z;

    }

    }

     

    int main()

    {

    int a, b,c;

    a=0;

    b=9;

        

         try{

             c=divide(a,b);

             cout<<c;

         }

         catch(const char * msg){

             cerr<<msg<<endl;

         }

    return 0;

    }

    Correct
    Incorrect
  2. Question 2 of 15
    2. Question

    What will be the output of the following program?

    #include <iostream>

     

    using namespace std;

     

    int main()

    {

    int x=-1;

    try{

         if(x<0)

         {

             throw”c++ Exception “;

             cout<<“x ix less than 0”;

         }  

    }

    catch(int x)

    {

         cout<<“Exception caught”;

    }

    return 0;

    }

    Correct
    Incorrect
  3. Question 3 of 15
    3. Question

    What will be the output of the following program?

    #include <iostream>

     

    using namespace std;

     

    int main()

    {

    int x=-1;

    try{

         if(x<0)

         {

             throw”c++ Exception”;

             cout<<“x ix less than 0”;

         }  

    }

    catch(const char * msg){

             cerr<<msg<<endl;

         }

    return 0;

    }

    Correct
    Incorrect
  4. Question 4 of 15
    4. Question

    What will be the output of the following program?

    int main()

    {

    try  {

        throw “C++ Exception”;

    }

    catch (const char *msg)  {

         cout << “Caught ” << msg;

    }

    catch (…)  {

         cout << “Default”;

    }

    return 0;

    }

    Correct
    Incorrect
  5. Question 5 of 15
    5. Question

    What will be the output of the following program?

    #include <iostream>

    using namespace std;

     

    int main()

    {

    float x=10.5;

    try  {

         if(x<20)

         {

             throw x;  

         }

    }

    catch (float x)  {

         cout <<x;

    }

    catch (…)  {

         cout << “Default”;

    }

    return 0;

    }

    Correct
    Incorrect
  6. Question 6 of 15
    6. Question

    What will be the output of the following program?

    #include <iostream>

    using namespace std;

     

    int main()

    {

    float x=10.5;

    int y=5;

    try  {

         if(x<10||y<x)

         {

             throw y;  

         }

    }

    catch (float x)  {

         cout <<x;

    }

    catch (…)  {

         cout << “Default”;

    }

    return 0;

    }

     

    Correct
    Incorrect
  7. Question 7 of 15
    7. Question

    What will be the output of the following program?

    #include <iostream>

    using namespace std;

     

    int main()

    {

    try{

         try{

             throw;

         }catch(int n){

             cout<<“caught”;

         }

         throw;

    }

    catch(int n){

         cout<<“caught1”;

    }

         

    }

    Correct
    Incorrect
  8. Question 8 of 15
    8. Question

    What will be the output of the following program?

    #include <iostream>

    using namespace std;

     

    int main()

    {

    try{

         try{

             throw 10;

         }catch(int n){

             cout<<“caught “;

         }

         throw;

    }

    catch(int n){

         cout<<“caught1”;

    }

         

    }

    Correct
    Incorrect
  9. Question 9 of 15
    9. Question

    What will be the output of the following program?

    #include <iostream>

    using namespace std;

     

    int main()

    {

    try{

         try{

             throw 10;

         }catch(int n){

             cout<<“caught “;

         }

         throw 10;

    }

    catch(int n){

         cout<<“caught1”;

    }

         

    }

    Correct
    Incorrect
  10. Question 10 of 15
    10. Question

    What will be the output of the following program?

    #include <iostream>

    using namespace std;

     

    int main()

    {

    try{

         try{

             throw “throw”;

         }catch(int n){

             cout<<“caught “;

         }

         throw “throw”;

    }

    catch(int n){

         cout<<“caught1”;

    }

    catch(…)

    {

         cout<<“Default”;

    }

         

    }

    Correct
    Incorrect
  11. Question 11 of 15
    11. Question

    Which among the following is not an advantage of exception handling?

    Correct
    Incorrect
  12. Question 12 of 15
    12. Question

    Which among the following is not a keyword that is used to handle exception in c++?

    Correct
    Incorrect
  13. Question 13 of 15
    13. Question

    What is protected code?

    Correct
    Incorrect
  14. Question 14 of 15
    14. Question

    What is the library used for standard exceptions in C++?

    Correct
    Incorrect
  15. Question 15 of 15
    15. Question

    What exception is thrown for a mathematical overflow?

    Correct
    Incorrect

Summary

Every C++ programmer should be familiar with exception handling. Now, you know how try and catch blocks works with their syntax and example. After knowing the importance of exception handling, we are sure you didn’t want to skip this topic. Hope, you like the tips and tricks that might come in handy whenever dealing with exceptions in C++.

We are waiting for your suggestion and feedback!

Exit mobile version