Next page | Contents page |

Throwing and catching exceptions

If the system detects an error it "throws an exception". You can do the same from your own code, using keyword throw. You can throw any object but since version 1.5 of JavaScript there has been a useful type for the purpose: Error. So you might write something like this in validating the input from a user that is intended to be an integer (whole number):

  var intRegExp = /^(\+|-)?[0-9]+$/;  
  // Regular expression for optional sign followed by 1 or more digits

  var text = document.getElementById ("myField").value;

  if (-1 == (intRegExp) throw new Error ("Not an integer");

  ... // Continue here of course if input matched the expression.

As it stands, detecting the error will make the program fail and the error message should show up in the browser's error console, as we discussed in Part 1.

However, you would probably want to recover from such an error. JavaScript therefore includes a mechanism for catching exceptions and handling them if they should be thrown. There are some new keywords to learn: try ... catch ... finally. You use them by writing a "try block":

    ... // some code that might throw exceptions
  catch (ex)
    ... // use the object ex to do something:
    ... // maybe an alert() to the user,
    ... // maybe something else
    ... // code that will be executed
    ... // regardless of what heppened in the
    ... // try and catch blocks; even if
    ... // there was a return - do this first

The catch and finally blocks are both optional but you must have at least one of them. The curly braces are also essential, even if a block only has one statement in it.

You can catch exceptions that the system throws because you made a mistake. So that can provide another debugging aid if you are stuck.

Will will see later how to determine the type of the exception object passed into the catch block, if it is not Error.

Next page | Contents page |