try/catch Blocks

To prevent your code from totally bombing out, use try/catch blocks that can handle problems inside your code. If JavaScript encounters an error when executing code in a try block, it will jump down and execute the catch portion instead of stopping the entire script. If no error occurs, then the whole try block will be executed, and none of the catch block will be executed.

For example, the following try/catch block tries to assign variable x to a value of an undefined variable named badVarNam:

try{
    var x = badVarName;
} catch (err){
    console.log(err.name + ': "' + err.message +  '" occurred when assigning x.'),
}

Notice that the catch statement accepts an err parameter, which is an error object. The error object provides the message property, which provides a description of the error. The error object also provides a name property that is the name of the error type that was thrown.

The code above results in an exception and the following message:

ReferenceError: "badVarName is not defined" occurred when assigning x.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset