Utilize goto for error handling
The following program illustrates how goto statement can be used for error handling in order to avoid unnecessary calculations:
// C++ Program to utilize goto for error handling
#include <iostream>
#include <limits>
using namespace std;
int main() {
double numerator = 10.0;
double denominator = 0.0;
double result;
if (denominator == 0) {
// Jump to cleanup if denominator is 0
goto cleanup;
}
// Perform the division
result = numerator / denominator;
cout << "Result: " << result << endl;
cleanup:
cerr << "Error: Division by zero is not allowed." << endl;
cout << "Program has finished executing." << endl;
return 0;
}
Output
ERROR!
Error: Division by zero is not allowed.
Program has finished executing.
Time Complexity: O(1)
Auxiliary Space: O(1)
How to Utilize the goto Statement in C++?
The goto statement in C++ is a control flow statement that allows the users to move the control flow from one part to another part of the program. In this article, we will learn how to utilize the goto statement in C++.