Rewrite the Java code of Section 14.4.6 that uses a finally clause in C++. Section 14.4.6 There

Question:

Rewrite the Java code of Section 14.4.6 that uses a finally clause in C++.


Section 14.4.6

There are some situations in which a process must be executed regardless of whether a try clause throws an exception and regardless of whether a thrown exception is caught in a method. One example of such a situation is a file that must be closed. Another is if the method has some external resource that must be freed in the method regardless of how the execution of the method terminates. The finally clause was designed for these kinds of needs. A finally clause is placed at the end of the list of handlers just after a complete try construct. In general, the try construct and its finally clause appear as

try {
. . .
}
catch (. . .) {
. . .
}
. . . //** More handlers
finally {
. . .
}

The semantics of this construct is as follows: If the try clause throws no exceptions, the finally clause is executed before execution continues after the try construct. If the try clause throws an exception and it is caught by a following handler, the finally clause is executed after the handler completes its execution. If the try clause throws an exception but it is not caught by a handler following the try construct, the finally clause is executed before the exception is propagated. A try construct with no exception handlers can be followed by a finally clause. This makes sense, of course, only if the compound statement has a throw, break, continue, or return statement. Its purpose in these cases is the same as when it is used with exception handling. For example, consider the following:

try {
for (index = 0; index < 100; index++) {
. . .
if (. . . ) {
return;
} //** end of if
. . .
} //** end of for
} //** end of try clause
finally {
. . .
} //** end of try construct

The finally clause here will be executed, regardless of whether the return terminates the loop or it ends normally.

Fantastic news! We've Found the answer you've been seeking!

Step by Step Answer:

Related Book For  book-img-for-question
Question Posted: