Errors handling in JavaScript using try catch

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

Error handling is an essential part of programming; we must implement code to handle errors correctly, here we see how to implement JavaScript errors handling with try catch example.

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.

catch runtime error in javascript try catch block

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 about how to use try catch block to handle error in javascript 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 and throw error in javascript code.

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.

 
JavaScript programming tutorials to learn JavaScript coding step by step, develop website using JavaScript and html.
Advanced JavaScript
Try catch in JavaScript error handling

javascript Interview Questions Answers
JavaScript Examples | JavaScript Online Course