Wondering why JavaScript doesn't include exception-handling constructs like its bigger cousins? Well, the newest version of JavaScript does - and this article tells you all about it, explaining how you can use the new Error object and the "try-catch" constructs to trap and resolve errors in script execution.
JavaScript also allows you to add a "finally" block to the "try-catch" block discussed previously. The "finally" block contains statements that are executed regardless of whether an exception is generated or not in the "try-catch" block.
try {
execute this block
} catch (error) {
execute this block if error
} finally {
execute this block after the try block
}
If an exception is encountered when running the code within the "try" block, JavaScript will stop execution at that point, and look for a "catch" block to handle it. Once the error has been handled (or if no "catch" block exists), control passes to the "finally" block.
Take a look at the next example to see how this works:
<script language="JavaScript">
// ask for user input
code = prompt("Enter some JavaScript code");
// run the code and catch errors if any generated
// after the error handling display goodbye message
try {
eval(code);
} catch (e) {
alert("The following error occurred: " + e.name + " - "
+ e.message); } finally {
alert ("Thank you for playing. Come back soon!");
}
</script>
Here's the output:
The following error occurred: TypeError - 'a' is undefined Thank you for playing. Come back soon!
It's important to note that the code in the "finally" block will be executed even if errors are encountered in the corresponding "try" block.