Arnaud Diederen aundro wrote:
try {
try {
throw "Error!!";
} finally {
document.write ("finally executed");
}
} catch (e) {
alert (e);
} finally {
alert ('last finally');
}
----snip----
.. and it works as expected. I must admit I don't really understand
what makes it work, while the other example fail.
throw new Error("My error") is not like some alert("An error happened")
;-)
If a block throws an error it says: "An oops happened which I cannot /
don't want to deal with. Anyone smarter than I am?"
Usually the "smarter partner" has to be in the catch block right here
or in a catch block somewhere higher. If no smart guy (appropriate
catch block) found then the program executes [finally] block and
aborts. Therefore the originally posted testcase is not from the real
life - it is a curiosity puzzle "what if?" In the real programming you
never throw exceptions "into space". There always *must* be a catch
block provided somewhere. Still even a pure curiosity is a good thing
;-) so here how does it work (this is taken from C# but similar to all
C-based languages):
1) If an exception is thrown, each catch clause is inspected in turn
for a type to which the exception can be assigned; be sure to order
them from most specific to least specific
2) when a match is found, the exception object is assigned to the
identifier and the catch statements are executed
3) if no matching catch clause is found, the exception percolates up to
any outer try block that may handle it
4) if a finally clause is included, it's statements are executed after
all other try-catch processing is complete
5) the [finally] clause executes wether or not an exception is thrown
or a break or continue are encountered
Note: If a catch clause invokes System.exit() the finally clause
WILL NOT execute.
So in the case like
try {
throw new Error('My error');
}
funally {
alert('Booh!');
}
Firefox considers your <script> block as self-enclosed system. After
reaching the top (<script> borders) and failing to find an appropriate
catch block, it returns control to [finally] and aborts right after.
Internet Explorer considers your <script> as a part of the global
JScript context. After reaching the top (<script> borders) and failing
to find an appropriate catch block, it forwards control further to the
JScript interpreter in hope that that one knows what to do with it.
Naturally JScript interpreter has not such exception registered in its
table and it does what it was instructed to do in such cases: it aborts
the execution. Therefore the control never gets a chance to come back
to [finally].
Hope it helps.