The program begins by prompting the user to enter two integers. The integers are input in the condition of the while
loop (line 28). Line 34 passes the values to function quotient
(lines 10–18), which either divides the integers and returns a result, or throws an exception (i.e., indicates that an error occurred) on an attempt to divide by zero. Exception handling is geared to situations in which the function that detects an error is unable to handle it.
As you learned in Section 7.10, try
blocks enable exception handling, enclosing statements that might cause exceptions and statements that should be skipped if an exception occurs. The try
block in lines 32–36 encloses the invocation of function quotient
and the statement that displays the division result. In this example, because the invocation of function quotient
(line 34) can throw an exception, we enclose this function invocation in a try
block. Enclosing the output statement (line 35) in the try
block ensures that the output will occur only if function quotient
returns a result.
Software Engineering Observation 17.3
Exceptions may surface through explicitly mentioned code in a try block, through calls to other functions and through deeply nested function calls initiated by code in a try block.