How to use Try Catch Throw in JavaScript

How to use Try Catch Throw in JavaScript
Table of Contents

How Javascript exception handling works. Try Catch Throw

Throw, and Try...Catch...Finally

The try statement defines a code block to run (to try).

The catch statement defines a code block to handle any error.

The finally statement defines a code block to run regardless of the result.

The throw statement defines a custom error.

Example Javascript exceptionExample Javascript exception

In this example we misspelled "alert" as "allert" to deliberately produce an error:

try {
    allert("Welcome to this test!");
}
catch(err) {
    document.getElementById("pDemo").innerHTML = err.message;
}

Implementing the Rollbar Javascript SDK helps speed up the error resolution flow. Here is the code example:

try {
    allert("Welcome to this test!");
}
catch(err) {
    Rollbar.error(err);
    document.getElementById("pDemo").innerHTML = err.message;
}

Track, Analyze and Manage Errors With Rollbar

Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing Javascript errors easier than ever. Try it today!

Build with confidence. Release with clarity.

Rollbar helps you track what breaks, understand why, and improve what comes next.

5K free events per month, forever
14-day full feature trial
Easy and quick installation
Get started in minutes

Plans starting at $0. Take off with our 14-day full feature Free Trial.