C++ program to demonstrate exception handling


Suppose there is a function that calculates some serious complex mathematical operations. But during the operations, some exceptions can occur. We have to handle the different types of exceptions that can occur and perform the following.

  • If the computer is unable to allocate the memory for computation, we have to print 'Memory Low!'
  • If any other C++-related exception occurs, we have to print 'Exception:' then the exception.
  • If something else happens, we print 'Unhandled exception'.

We are given an array that contains a pair of values, and we pass it to the function. If any exception occurs, we handle it, or otherwise, we print the output value.

We only have to handle the exceptions disregarding the mechanisms of the function generating the exceptions.

So, if the input is like arr = {{361643035132, 2297873642249}, {-17, 15}};, then the output will be −

Memory Low!
Exception: val1 is negative

The first pair of values is too large to be handled, so 'Memory low' is printed. The first value of the second pair is negative. The function provided cannot work with that so it generates/throws an exception 'val1 is negative',

To solve this, we will follow these steps −

  • for initialize i := 0, when i < t, update (increase i by 1), do −
    • val1 := values[i, 0]
    • val2 := values[i, 1]
    • try,
      • print(foo(val1, val2))
    • if the memory can not be allocated (bad_alloc exception is caught), then
      • print("Memory Low!")
    • otherwise, if any other standard C++ exception e is caught, then
      • print("Exception: ")
      • print details of the exception
    • otherwise if any other exception is caught, then
      • print("Unhandled Exception")

Example

Let us see the following implementation to get better understanding −

#include <iostream>
#include <exception>
#include <string>
#include <stdexcept>
#include <vector>
#include <cmath>
using namespace std;

class Solution {
private:
   static int value;
public:
   static int foo(long long val1, long long val2) {
      value += 1;
      if(val1 < 0) {
         throw std::invalid_argument("val1 is negative");
      }
      vector<int> vectorList(val1, 0);
      int r = -1, c = sqrt(-1);
      if(val2 == 0) throw 0;
      r = (val1 / val2) * r;
      int ans = vectorList.at(val2);
      return r + val1 - val2 * ans;
   }
   static int getVal() {
      return value;
   }
};
int Solution::value = 0;

void solve(int t, long int values[][2]) {
   for (int i = 0; i < t; i++) {
      long long val1, val2;
      val1 = values[i][0];
      val2 = values[i][1];
      try {
         cout << Solution::foo(val1, val2) << '\n';
      }
      catch (const std::bad_alloc&) {
         cout << "Memory Low!\n";
      }
      catch (const std::exception& e) {
         cout << "Exception: " << e.what() << '\n';
      }
      catch (...) {
         cout << "Unhandled Exception\n";
      }
   }
}
int main() {
   long int arr[][2] = {{361643035132, 2297873642249}, {-17, 15}};
   solve(2, arr);
}

Input

long int arr[][2] = {{361643035132, 2297873642249}, {-17, 15}};
solve(2, arr);

Output

Memory Low!
Exception: val1 is negative

Updated on: 12-Oct-2021

209 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements