divide_throw_catch_primitive
Now let us add a try..catch block which should generally be in one of the caller functions. The syntax is:
  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.

38
 
1
#include <iostream>
2
#include <string>
3
#include <stdexcept>
4
using namespace std;
5
int divide(int num, int denom)
6
{
7
   if(denom == 0){
8
      throw 0;
9
   }
10
   else if (num == 0) {
11
      throw string("Num is 0...Bad!");
12
   }
13
   cout << "Normal case" << endl;
14
   return(num/denom);
15
}
16
int f1(int x)
17
{
18
   int res = -1;
19
   // Add your try catch block here
20
   res = divide(x, x-2);       
21
      
22
      
23
   // What should I return though if I catch an error?
24
   // How would main know how to interpret res?
25
   // Generally it is better to put the exception handling
26
   // in the function that can do something about the root cause
27
   return res;
28
}
29
30
int main()
31
{
32
   int res = -1, a;
33
   cout << "Enter: " << endl;
34
   cin >> a;
35
   res = f1(a);
36
   cout << res << endl;
37
   return 0;
38
}