try statement lets you test a block of code for errors.
catch statement lets you handle the error.
throw statement lets you create custom errors.
finally statement lets you execute code, after try and catch, regardless of the result.
Errors can be coding errors made by the programmer, errors due to wrong input, and other unforeseeable things.
In this example we have written alert as adddlert to deliberately produce an error:
try statement allows you to define a block of code to be tested for errors while it is being executed.
catch statement allows you to define a block of code to be executed, if an error occurs in the try block.
catch come in pairs:
throw statement allows you to create a custom error.
Technically you can throw an exception (throw an error).
Boolean or an
If you use
throw together with
catch, you can control program flow and generate custom error messages.
This example examines input. If the value is wrong, an exception (err) is thrown.
The exception (err) is caught by the catch statement and a custom error message is displayed:
The code above is just an example.
You can read more about forms validation in a later chapter of this tutorial.
finally statement lets you execute code, after try and catch, regardless of the result:
The error object provides two useful properties: name and message.
|name||Sets or returns an error name|
|message||Sets or returns an error message (a string)|
Six different values can be returned by the error name property:
|EvalError||An error has occurred in the eval() function|
|RangeError||A number "out of range" has occurred|
|ReferenceError||An illegal reference has occurred|
|SyntaxError||A syntax error has occurred|
|TypeError||A type error has occurred|
|URIError||An error in encodeURI() has occurred|
The six different values are described below.
EvalError indicates an error in the eval() function.
RangeError is thrown if you use a number that is outside the range of legal values.
For example: You cannot set the number of significant digits of a number to 500.
ReferenceError is thrown if you use (reference) a variable that has not been declared:
SyntaxError is thrown if you try to evaluate code with a syntax error.
TypeError is thrown if you use a value that is outside the range of expected types:
URIError is thrown if you use illegal characters in a URI function:
Mozilla and Microsoft defines some non-standard error object properties:
Do not use these properties in public web sites. They will not work in all browsers.