web training room for online courses
Learn JavaScript, Free JavaScript Tutorial for Beginners, Interactive JavaScript Examples

Errors handling in JavaScript try, catch, finally

How to handle JavaScript errors using try, catch

Like all other programming language JavaScript also has a way to write try, catch, finally to capture runtime error and process the error

So as a good programming practice you should learn how to capture runtime error, this also helps to provide a better user experience, avoid any unexpected application error, catch them and keep user friendly message on interface.

Here is how you can write try catch block in JavaScript

try {            
    // some code that may produce error
} catch (e) {
    // this will run only if any errors            

Now if you notice how the error object gets access to catch block catch (e).

Now let's do some experiment how try catch handle error in real time.

So write a function with some code that will produce error
Then we call the function in button click to see how the error get caught and a user-friendly message been displayed

<script> function WelcomeUser(userName) {
try {
alert("Hello " + userNameNoVar);
catch (e) {
} </script>

Now we call the above function on button click

You probably see "ReferenceError: userNameNoVar is not defined".
That was the error message got caught inside catch block, because the variable name in argument was userName and in alert we have appended a wrong variable name userNameNoVar

catch and throw error in javascript

You also can catch an throw the error in javascript.

But you need to logically think where the final error will be caught, because JavaScript is normally used for client side programming and you should not show the system error message to end user.
So be careful about throwing error in JavaScript code

function WelcomeUser(userName) {
try {
alert("Hello " + userNameNoVar);
catch (e)
throw e;

Name Email Website
JavaScript errors handling try, catch, finally, Learn JavaScript Syntax

JavaScript Tutorial