Home >Backend Development >C++ >C++ program example showing exception handling
Suppose there is a function that calculates some complex mathematical operations. However, some exceptions may occur during the operation. We have to handle the different types of exceptions that may occur and do the following.
We have an array containing a pair of values and pass it to a function. If any exception occurs, we handle it, otherwise print out the value.
We only need to handle exceptions, regardless of the mechanism by which functions generate exceptions.
So if the input is 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 handle, So it prints "Out of Memory". The first value of the second pair of values is a negative number. The provided function cannot be handled, so the exception "val1 is negative" is generated/thrown,
To solve this problem, we will follow the following steps −
Let us look at the following implementation for 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); }
long int arr[][2] = {{361643035132, 2297873642249}, {-17, 15}}; solve(2, arr);
Memory Low! Exception: val1 is negative
The above is the detailed content of C++ program example showing exception handling. For more information, please follow other related articles on the PHP Chinese website!