Home arrow JavaScript arrow Page 6 - JavaScript Exception Handling

The Final Solution - JavaScript

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.

  1. JavaScript Exception Handling
  2. Anatomy Of An Exception
  3. Playing Catch
  4. Being Verbose
  5. All For One...
  6. The Final Solution
  7. Raising The Bar
  8. Endzone
By: icarus, (c) Melonfire
Rating: starstarstarstarstar / 239
August 14, 2003

print this article



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 {
} catch (e) {
alert("The following error occurred: " + e.name + " - " + e.message); } finally {
alert ("Thank you for playing. Come back soon!");


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.

>>> More JavaScript Articles          >>> More By icarus, (c) Melonfire

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort


- Javascript for Beginners: An Introduction
- Introduction to JavaScript
- Adding Elements to a Tree with TreeView jQue...
- Using the Persist Argument in a TreeView jQu...
- Using Unique and Toggle in a TreeView jQuery...
- Using Event Delegation for Mouseover Events ...
- Using the Animate Option in a Treeview jQuer...
- Using HTML Lists with Event Delegation in Ja...
- Opened and Closed Branches on a TreeView jQu...
- Mouseover Events and Event Delegation in Jav...
- Creating a TreeView JQuery Hierarchical Navi...
- Event Delegation in JavaScript
- A Look at the New YUI Carousel Control
- Working with Draggable Elements and Transpar...
- Displaying Pinned Handles with Resizable Con...

Developer Shed Affiliates


Dev Shed Tutorial Topics: