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;
}
try {
    allert("Welcome to this test!");
}
catch(err) {
    Rollbar.error(err);
    document.getElementById("pDemo").innerHTML = err.message;
}

In this scenario in the try method allert is misplaced so it will print allert is not defined as an error and the catch err won’t get processed so if we add the rollbar then it won’t disturb the flow of the execution and it will not display the the try method error and it will execute the catch err and display the message that we try to show.

We need to add script source for the rollbar.js

https://cdn.rollbar.com/rollbarjs/refs/tags/vX.X.X/rollbar.min.js
where X.X.X would be replaced with the version number of the latest release.

Leave a comment

Your email address will not be published. Required fields are marked *