try {
// Ask the user to enter a number
var n = prompt("Please enter a positive integer", "");
// Compute the factorial of the number, assuming that the user's
// input is valid
var f = factorial(n);
// Display the result
alert(n + "! = " + f);
}
catch (ex) { // If the user's input was not valid, we end up here
// Tell the user what the error is
alert(ex);
}
This example is a try/catch statement with no
finally clause. Although
finally is not used as often as
catch, it can often be useful. However, its
behavior requires additional explanation. The
finally clause is guaranteed to be executed if any
portion of the try block is executed, regardless
of how the code in the try block completes. It is
generally used to clean up after the code in the
try clause.
In the normal case, control reaches the end of the
try block and then proceeds to the
finally block, which performs any necessary
cleanup. If control leaves the try block because
of a return, continue, or
break statement, the finally
block is executed before control transfers to its new destination.
If an exception occurs in the try block and there
is an associated catch block to handle the
exception, control transfers first to the catch
block and then to the finally block. If there is
no local catch block to handle the exception,
control transfers first to the finally block and
then propagates up to the nearest containing catch
clause that can handle the exception.
If a finally block itself transfers control with a
return, continue,
break, or throw statement, or
by calling a method that throws an exception, the pending control
transfer is abandoned and this new transfer is processed. For
example, if a finally clause throws an exception,
that exception replaces any exception that was in the process of
being thrown. If a finally clause issues a
return statement, the method returns normally,
even if an exception has been thrown and has not yet been handled.