How to Write Clean Exception Handling Code in C++ Language

In this article, we will learn How to Write Clean Exception Handling Code in C++ and why it is important to learn and understand. This article also has the best examples to help you learn quickly and easily.

In C++, exception handling is done with three keywords: try, throw statement, and catch statement. The try statement lets you set up a block of code to be checked for errors while it is being run. The throw keyword sends an exception when a problem is found, which lets us make a custom error.

Exception handling is important if you want to write code that works in unusual situations or, at the very least, tells a user what went wrong.

How to Write Clean Exception Handling Code in C++
How to Write Clean Exception Handling Code in C++

How do you write exception handling in C++?

In C++, the words Try, Throw, and Catch are used to handle errors. The Try expression shows which part of the code could have an error occurs. It could do things like divide two numbers or go through a list of numbers over and over again. The exception is taken care of by the Throw expression.

What exceptions allow us to separate in C++?

A C++ exception is a way for a program to deal with something unusual that happens while it is running. Exceptions are a way to move control of a program from one part to another.

This lets us separate code for handling errors from code for normal control flow, which makes our code easier to read.

How many types of exception handling are there in C++?

There are 2 kinds of exceptions:

  • Synchronous
  • Asynchronous

What is exception safe code in C++?

An exception-safe programming language is writing code so that if a piece of code could throw an exception as stack unwinding, the state of the program doesn’t get messed up, and resources don’t get wasted. Using traditional methods to get this right often leads to code that is hard to understand, ugly, and fragile.

Which keyword is used to handle an exception?

The throw keyword is used to throw an explicit exception. The try-catch block is used to handle exceptions thrown by other codes.

Why do we need exception handling in C++?

Exception handling is a way to keep code that looks for and responds to unusual situations separate from the rest of your program.

Keep in mind that something out of the ordinary is not always a mistake. When a function finds something out of the ordinary, you show this with an object and return 0.

C++ Runtime Exception Handling

In C++, exception handling is a process for error handling that happens at runtime. We handle exceptions so that, even if there are runtime errors, the application can still work normally.

For Example:

Let’s start by writing a script called bmi.cpp. We will add headings for <iostream> and <string>. We can write to the standard input and output streams with the <iostream> heading. We can make string identifiers with the <string> heading.

#include <iostream>
#include <string>
using namespace std;

When the program is built and run, it will ask for the user’s name. To do this, we need to set up a string variable for the name and two float variables for the weight and height, respectively:

// Main() function: where the execution of program begins
int main()
{

    float weight;
    float height;
    string name;
}

Next, let’s add the code that will ask for the user’s name:

// Main() function: where the execution of program begins
int main()
{
    float weight;
    float height;
    string name;
    cout << "Please Enter your Name: \n";
    cin >> name;
}

In terminal, we run the following command to make our code work:

g++  bmi.cpp

And we run it using the following command:

./a.out

The following is the result:

Please Enter your Name:

Now, let’s write code that greets the user when they type in their name and asks for their weight:

// Main() function: where the execution of program begins
int main()
{
    float weight;
    float height;
    string name;
    cout << "Please Enter your Name: \n";
    cin >> name;
    cout << "Hello " << name << ", Please enter your weight in Kg \n";
}

If we compile and run, we get the following:

Hello Glenn, please enter your weight in Kg

Then, we can add the weight logic as user input:

int main()
{
    float weight;
    float height;
    string name;
    cout << "Please Enter your Name \n";
    cin >> name;
    cout << "Hello " << name << ", please enter your weight in Kg \n";
    cin >> weight;
}

The user will be asked to put in a weight value. Now, let’s add logic so that when a user enters their weight in kilograms, we ask them for their height in meters:

int main()
{ 
    float weight;
    float height;
    string name;
    cout << "Please Enter your Name: \n";
    cin >> name;
    cout << "Hello " << name << ", please enter your weight in Kg \n";
    cin >> weight;
    cout << "Thank you " << name << ", now please enter your height in meters \n";
    cin >> height;  
}
Thank you, Glenn now please enter your height in meters

We can now use this information to figure out a BMI. Weight/Height2 is the formula for BMI. I typed in my name, Glenn, my weight, 90 kg, and my height, 1.92 m:

int main()
{
    float weight;
    float height;
    string name;
    float bmi;
    cout << "Please Enter your Name: \n";
    cin >> name;
    cout << "Hello " << name << ", please enter your weight in Kg \n";
    cin >> weight;
    cout << "Thank you " << name << ", now please enter your height in meters \n";
    cin >> height;  
    bmi = weight/(height*height);
    cout << "Your BMI is: " << bmi <<"\n";
}

With 173.736 cm of height and 61 kg of weight, we can get a BMI of 20.2:

Your BMI is: 20.2

Now, let’s try giving height a value of zero:

Your BMI is: inf

We can see that putting 0 for height gives us a BMI of “inf,” which means “infinity.” This is obviously not a value that helps the user, and it may only cause confusion.

Instead of showing “infinity,” we should try to catch this error and show the user a message that they gave an invalid height value. By catching a runtime error, we can do this.

First, we need to import stdexcept at the top of our script so we can use runtime error:

#include<stdexcept>

Next, we can put our BMI calculation logic into a function:

float BMI_calculator(float weight, float height){
	if (height == 0){
	throw runtime_error("You attempted to calculate BMI with an invalid value of zero for height \n");
	}
	return weight/(height*height);
}

Then, we can make changes to our main function to try to figure out BMI:

 try{
        bmi = BMI_calculator(weight, height);
        cout << "Your BMI is: " << bmi <<"\n";
    }

And catch the runtime error when it happens. If this happens, we show the message “Warning: You tried to calculate BMI with an invalid value of zero for height.”

 catch (runtime_error&e){
        cout<< "Warning: "<< e.what();
    }

Then, we compile our code and run it, giving zero as the input for height. We see the following message on the screen:

Warning: You attempted to calculate BMI with an invalid value of zero for height

We can see that this message is much clearer and more helpful than the old one, “Your BMI is: inf.”

Length Error Exception Handling

When working with vectors as a standard library, the length error exception is another common error. To show how this kind of error can happen, we’ll create a function that figures out the total amount of monthly contributions to a retirement account. First, let’s define a C++ script called stack contributions.cpp.

For Example:

int main(){
	int months;
	int current_month = 1;
	cout << "Please enter the number of months: \n";
	cin >> months;
	try{
   	    std::vector<float> contributions(months); //float contributions[months];
   	    float initial_contrbution = 100;
   	    float sum_contributions = 0;
   	    contributions[1] = initial_contrbution;
   	    while (current_month <= months){
    	        contributions[current_month + 1] =1.02*contributions[current_month];
    	        cout << "Month " << current_month << " contribution is: " << contributions[current_month]<< endl;
    	        sum_contributions += contributions[current_month];
    	        current_month++;
    }
   	cout<<"Sum of contributions for " << months << " months is: "<<sum_contributions << endl;
 
     catch (const std::length_error& le) {
      	    std::cerr << "Length of " << le.what() << " can't be negative \n";
	}

	}
}

Now, if we compile, run, and give a negative value for months, we handle the error correctly:

Please enter the number of months: -6
Length of vector can't be negative

Summary

This article discusses how to write clean exception handling code in C++. It also tackles types of exceptions, exception safe code, keywords used to handle exceptions, runtime exceptions, and length error exception handling.

I hope this lesson has helped you learn a lot. Check out my previous and latest articles for more life-changing tutorials which could help you a lot.

Leave a Comment