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

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

Examples

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

</>
Copy
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

<!DOCTYPE html>
<html lang="en">
<body>
    <pre id="output"></pre>
    <script>
        try {
            var x = 16;
            var y = x.toUpperCase();
        } catch (err) {
            displayOutput = 'The following error occurred.\n'
            displayOutput += err;
            displayOutput += '\n\nWe have handled this error successfully.';
        }
        document.getElementById('output').innerHTML = displayOutput
    </script>
</body>
</html>

Conclusion

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