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:

Exception Handling in C++

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-

Examples of exception handling in C++

Output-

Output of Examples of exception handling in C++

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.

  • If you wish to catch all the exceptions in your code, you might want to use the “catch-all” statement which appears like this:

catch (…)

  • You cannot perform implicit type conversion for primitive data types. You need to be careful while writing statements like:

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.

  • C++ gives you the provision to throw an exception without having to catch it. Although it might result in some anomalous behavior, still it provides flexibility to the user to define the catch statement.
  • If you are working with classes, it is important to first catch all the exceptions of the derived class before that of the base class.
  • C++ allows us to work with nested try-catch statements. In addition to that, we can even re-throw an exception by using the throw keyword again.

Quiz on Exception Handling in C++

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!

Your opinion matters
Please write your valuable feedback about DataFlair on Google

follow dataflair on YouTube

Leave a Reply

Your email address will not be published. Required fields are marked *