JavaScript Try Catch

JavaScript Try Catch statement is used to try a block of code, and if in case there are any errors, we can catch those errors and handle them accordingly.

Syntax

The syntax of try-catch statement in JavaScript is

try {
    //code that has potential to throw errors
} catch (err) {
    //handle this error
}
ADVERTISEMENT

Examples

Consider the following code, where we are trying to call toUpperCase() method on a number. This piece of code throws TypeError.

var x = 16;
var y = x.toUpperCase();

In the following example, we will use try-catch statement, to handle this error. We surround the code that has potential to throw an error in try block, and the code to handle any error in catch block.

index.html

Conclusion

In this JavaScript Tutorial, we learned about try-catch statement in JavaScript, its syntax and usage with examples.