try { // statements or calls // that may generate exceptions } catch(type1 arg_name){ // code to be executed if type1 is thrown from somewhere in the try block } catch(type2 arg_name){ // code to be executed if type2 is thrown from somewhere in the try block } catch(...){ // code to be executed if any other type of exception is thrown in the try block }Add a catch block to f1() so that dividing by 0 in divide() will not cause the program to crash but simply print a message Error!.
In addition, let's add a dummy error case where we assume a number of 0 is BAD (it really isn't but just so you can see two or more errors/exceptions may be checked in a single function and each can throw a different type. If we catch this case, let's just print out the string that was thrown.
using namespace std;
int divide(int num, int denom)
{
if(denom == 0){
throw 0;
}
else if (num == 0) {
throw string("Num is 0...Bad!");
}
cout << "Normal case" << endl;
return(num/denom);
}
int f1(int x)
{
int res = -1;
// Add your try catch block here
res = divide(x, x-2);
// What should I return though if I catch an error?
// How would main know how to interpret res?
// Generally it is better to put the exception handling
// in the function that can do something about the root cause
return res;
}
int main()
{
int res = -1, a;
cout << "Enter: " << endl;
cin >> a;
res = f1(a);
cout << res << endl;
return 0;
}