Free Web Development Online Tutorials, Learn to Code
JavaScript error handling best practices, Handling runtime JavaScript errors try catch, javascript await error handling

JavaScript Errors handling try, catch, finally

JavaScript try catch example

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

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

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;
    }
}

javascript asynchronous error handling

Here is an example of how you can implement error handling in async JavaScript function; in following example i am calling “checkUser” method from async “myAsyncMethod” function.

let checkUser = async function(username, password){
try {
//let result = setTimeout(() => console.log("Tick"), 500);
        console.log("Welcome "+ username);
        throw new Error("some error message");
        //return result;
    }
    catch (ex)
    {
        console.log(ex)
    }
 };

async function myAsyncMethod() {
    try {
       let result= await checkUser("u1","p1");
       console.log(result);
    } catch (e) {
        console.error(e);
    } finally {
        console.log('we reached finally block');
    }
}

Now if you just call myAsyncMethod(), You will be able to see the sequence of all events within the function and how an error detail is being captured.

Comment
Name
Email
Website
Subscribe
JavaScript Examples | JavaScript Online Course