Exception-Handling Advantages in C++

Exception handling enables the caller of the function to process the exception thrown from a function.

Listing 16.3 demonstrates how an exception is created, thrown, caught, and handled. You may wonder about the benefits. To see them, we rewrite Listing 16.3 to compute a quotient using a function as shown in Listing 16.4.

Listing 16.4 QuotientWithFunction.cpp

1 #include <iostream>

2 using namespace std;

4 int quotient(int number1, int number2)

5 {

6    if (number2 == 0)

7    throw number1;

8
9   
return number1 / number2;
10 }
11
12
int main()
13 {
14   
// Read two integers
15    cout << “Enter two integers: “;
16   
int number1, number2;
17    cin >> number1 >> number2;
18
19   
try
20    {
21       
int result = quotient(number1, number2);
22       cout << number1 <<
” / ” << number2 << ” is ”
23       << result << endl;
24    }
25   
catch (int ex)
26    {
27       cout <<
“Exception from function: an integer ” << ex <<
28       
” cannot be divided by zero” << endl;
29    }
30
31    cout <<
“Execution continues …” << endl;
32
33   
return 0;
34 }

Function quotient (lines 4-10) returns the quotient of two integers. If number2 is 0, it can­not return a value. So, an exception is thrown in line 7.

The main function invokes the quotient function (line 21). If the quotient function executes normally, it returns a value to the caller. If the quotient function encounters an exception, it throws the exception back to its caller. The caller’s catch block handles the exception.

Now you see the advantages of using exception handling. It enables a function to throw an exception to its caller. Without this capability, a function must handle the exception or terminate the program. Often, the called function does not know what to do in case of error. This is typically the case for the library function. The library function can detect the error, but only the caller knows what needs to be done when an error occurs. The fundamental idea of exception handling is to separate error detection (done in a called function) from error han­dling (done in the calling function).

Source: Liang Y. Daniel (2013), Introduction to programming with C++, Pearson; 3rd edition.

Leave a Reply

Your email address will not be published. Required fields are marked *