Scripter Javascript Tutorial
javascriptmusiclogicscripterbookexcerpttutorial96 The try...catch
Statement
The intent of try...catch is to catch errors in specific
tasks before they cause problems. The try...catch statement
is most effective with one to a few lines of code intended to do one
specific thing within a function. This make debugging easy because very
specific errors can be written to the console and handled in a way which
won’t interfere with the rest of the script. The
try...catch statement works basically the same as the
if statement.
try {
<code to be attempted>
} catch ( error ) {
<code to handle the error>
}In the above example:
Line 1: The
trykeyword opens the try...catch statement.Line 2: Code to be attempted is contained within the curly braces. Whenever there is an error in that code, then the script immediately jumps to the
catchblock.Line 3: The
catchblock is similar to a function, with an argument passed containing the error. In this example, the argument is named “error” but could just as easily be any valid variable name.Line 4: Code intended to report and/or handle the error is contained within the curly braces.