console
.
log
(
err
.
stack
);
}
try
{
d
();
}
catch
(
err
) {
console
.
log
(
err
.
stack
);
}
Running this example in Firefox yields the following console output:
a: calling b
b: calling c
c: throwing error
c@debugger eval code:13:1
b@debugger eval code:8:4
a@debugger eval code:3:4
@debugger eval code:23:4
d: calling c
c: throwing error
c@debugger eval code:13:1
d@debugger eval code:18:4
@debugger eval code:29:4
The lines with the at signs in them are the stack traces, starting with the “deepest”
function (
c
), and ending with no function at all (the browser itself). You can see that
we have two different stack traces: one showing that we called
c
from
b
, which was
called from
a
, and one that
c
was called directly from
d
.
try...catch...finally
There are times when the code in a
try
block involves some sort of resource, such as
an HTTP connection or a file. Whether or not there is an error, we want to free this
resource so that it’s not permanently tied up by your program. Because the
try
block
can contain as many statements as you want, any one of which can result in an error,
it’s not a safe place to free the resource (because the error could happen before we
have the chance to do so). It’s also not safe to free the resource in the
catch
block,
because then it won’t get freed if there is no error. This is exactly the situation that
demands the
finally
block, which gets called whether or not there is an error.
Because we haven’t covered file handling or HTTP connections yet, we’ll simply use
an example with
console.log
statements to demonstrate the
finally
block:
try
{
console
.
log
(
"this line is executed..."
);
throw
new
Error
(
"whoops"
);
console
.
log
(
"this line is not..."
);
}
catch
(
err
) {
console
.
log
(
"there was an error..."
);
try...catch...finally | 173