C++

C++ Try-Catch-Finally

C++ provides the “try-catch” method for handling the exceptions. When an exception occurs in the C++ program, these “try-catch” methods aid in shifting the control from one part of the program’s code to the other. An exception is a glitch that appears while a program is running. When an extraordinary situation, such as trying to divide by zero, occurs while a program is executing, a C++ exception is raised and we handle this situation by simply utilizing the “try-catch” method in our codes. It contains three keywords: “try”, “catch,” and “throw”. The “throw” keyword is used to throw the exception in other code’s parts. The C++ programming doesn’t facilitate us with the “finally” keyword, but we can use the “try”, “catch”, and “throw” keywords in C++ codes.

Example 1:

The “iostream” is included here, the header file in which several functions are declared. We use these functions which are declared in this header file in our code, so we include this header file. After this, we have the “std” which is placed here as functions like “cin” and “cout” are also defined in it. We don’t need to type “std” with all these functions if we add the “namespace std” at the start of our code. After this, the “main()” function is invoked here which is also referred to as the driver code of the C++ program.

Then, we utilize the “try” keyword here in which we initialize “my_num1” with the “35” value. It is the “int” data type variable here. Now, we place this variable inside “if” and place a condition that says that “my_num1” must be greater than or equal to “98”. If the given condition is satisfied, it moves ahead inside “if” and executes the statement that is written here. We utilize the “cout” and insert a message to display when the condition is satisfied.

After this, we use the “throw” keyword after placing “else”. In this “throw” keyword, we pass “my_num1” as the parameter. We add the “catch” part below this. We insert “my_num2” as the parameter of “catch()” and then use the “cout” again inside this “catch” part. This part executes only when an exception occurs in the “try” part.

Code 1:

#include <iostream>
using namespace std;
int main() {
  try {
    int my_num1 = 35;
    if (my_num1 >= 98) {
      cout << "The Access is granted here.";
    } else {
      throw (my_num1);
    }
  }
  catch (int my_num2) {
    cout << "The Access is denied here." << endl ;
    cout << "The number is: " << my_num2;  
  }
  return 0;
}

Output:
The number that we entered is “35” which is less than “98”. So, the exception occurs there and the “catch()” part is displayed. The access to the “try” part is denied.

Example 2:

We place the “iostream” header file here and the “namespace std”. After this, we create a “division()” function in which we place two parameters which are the “numerator” and “denominator” of the “int” data type. We set the data type of this “division” function to “double”.

Below this, we add “if()” in which we add the condition that the denominator is equal to zero. After this, we use the “throw” keyword and type a message there. This message is rendered whenever the exception occurs in this code according to the condition. Below this, we utilize the “return” keyword in which we place “numerator/denominator”. So, it returns the result of the division. Now, the “main()” function is called.

After this, “num1” and “num2” are initialized as the “int” variables and assign “89” and “0” to them respectively. Then, we initialize the “result” of the “double” data type. Here, we utilize the “try” keyword. In this part, we add this “result” variable and assign the “division()” function to this variable. We pass two parameters to this function: “num1” and “num2”. Below this, we display the “result” that we get after applying the “division()” function. After this, we also utilize the “catch” and place the “const char* msg” to display the message that we previously added.

Code 2:

#include <iostream>
using namespace std;
double division(int numerator , int denominator ) {
   if( denominator  == 0 ) {
      throw "Division by zero is not possible here!";
   }
   return (numerator/denominator );
}
int main () {
   int num1 = 89;
   int num2 = 0;
   double result = 0;
   try {
      result = division(num1, num2);
      cout << result << endl;
   } catch (const char* msg) {
     cerr << msg << endl;
   }
   return 0;
}

Output:
The number that we previously inserted as the denominator is “0”. So, the exception occurs in the code and it displays the given message.

Example 3:

The “multiplication()” function is created here in which we place the “value” and “multiplier” as the parameters of the “int” data type. Then, we utilize “if” in which we add a multiplier condition that is equal to zero. Then, “throw” is placed where we add a statement. Then, we have the “return” where we place the “value * multiplier” variables that we previously declared. So, it returns the multiplication result here.

After this, we call the “main()” where we declare the “int value1” and “int value2” with the values of “34” and “0”, respectively. The “int m_res” is also declared and then called the “multiplication()” function here. After performing this function, the result is now saved in the “m_res” variable and then displayed. Subsequently, we employ the “catch” function and insert the “const char* msg” to exhibit the message that we previously added in the “throw” part.

Code 3:

#include <iostream>
using namespace std;
double multiplication(int value , int multiplier ) {
   if( multiplier  == 0 ) {
      throw "We don't multiply the value with zero!";
   }
   return (value * multiplier );
}
int main () {
   int value1 = 34;
   int value2 = 0;
   int m_res;
   try {
      m_res = multiplication(value1, value2);
      cout << m_res << endl;
   } catch (const char* msg) {
     cerr << msg << endl;
   }
   return 0;
}

Output:
Since the value that we previously entered has “0” as the multiplier, the code has an exception which causes the notice to be displayed here.

Example 4:

Here, we build the “multiply()” function and pass in the “number1” and “number2” as the parameters of the “int” data type. Next, we use the “if” operator to add a condition to it which is a multiplier that is less than or equal to zero. After that, the statement is added where “throw” is supposed to be. The multiplication result is then returned in the “return” section where we insert the “number1 * number2” variable that we previously declared.

Subsequently, we invoke the “main()”function and assign the “34” and “12” values to “int newNumber1” and “int newNumber2”, respectively. Here, the “multiply()”function is called after the declaration of the “int mResult”. Now, the outcome of this function is stored in the “mResult” variable and is rendered in the following. We then use the “catch” function and add the “const char* msg” to display the message that we wrote in the “throw” section.

Code 4:

#include <iostream>
using namespace std;
double multiply(int number1 , int number2 ) {
   if( number2 <= 0 ) {
      throw "We don't multiply the value with zero or negative value!";
   }
   return (number1 * number2 );
}
int main () {
   int newNum1 = 34;
   int newNum2 = 12;
   int mResult;
   try {
      mResult = multiply(newNum1, newNum2);
      cout << "The result of multiplication is " << mResult << endl;
   }
   catch (const char* msg) {
     cerr << msg << endl;
   }
   return 0;
}

Output:
The value that we add is “12” on which we add the condition. So, the “multiply()” function is performed since the condition is not true. The result of the multiplication is displayed. The “try” part is executed here.

Conclusion

The “try-catch” concept and the codes in this guide are studied in detail. We thoroughly explored this “try-catch” concept and showed how it works in C++ programming. We defined that the “throw” term creates an exception when an error is found which lets us write our unique code. Using the “catch” expression, we can specify a block of code to be run if an exception appears in the “try” part.

About the author

Omar Farooq

Hello Readers, I am Omar and I have been writing technical articles from last decade. You can check out my writing pieces.