Exception Handling in C++: Exception Specification

You can declare potential exceptions a function may throw in the function header.

An exception specification, also known as throw list, lists exceptions that a function can throw. So far, you have seen the function defined without a throw list. In this case, the func­tion can throw any exception. So, it is tempting to omit exception specification. However, this is not a good practice. A function should give warning of any exceptions it might throw, so that programmers can write a robust program to deal with these potential exceptions in a try-catch block.

The syntax for exception specification is as follows:

returnType functionName(parameterList) throw (exceptionList)

The exceptions are declared in the function header. For example, you should revise the check function and the Triangle constructor in Listing 16.13 to specify appropriate excep­tions as follows:

1 void check(double side) throw (NonPositiveSideException)
2 {
3     
if (side <= 0)
4       
throw NonPositiveSideException(side);
5 }
6
7 Triangle(
double side1, double side2, double side3)
8   
throw (NonPositiveSideException, TriangleException)
9 {
10    check(side1);
11    check(side2);
12    check(side3);
13
14   
if (!isValid(side1, side2, side3))
15       
throw TriangleException(side1, side2, side3);
16
17   
this->side1 = side1;
18   
this->side2 = side2;
19   
this->side3 = side3;
20 }

Function check declares that it throws NonPositiveSideException and constructor Triangle declares that it throws NonPositiveSideException and TriangleException.

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 *