JavaScript Error Handling

Leave a comment

JavaScript contains different ways to handle errors.

One way is using try/catch/finally. In the example below, variable y does not exist.

try
{
    var x = 1 + y;
    console.log(t);
}
catch(e)
{
    console.log("Error: " + e);
}
finally
{
    console.log("Run finally");
}

Running this produces:

Note you can also use name, message and stack to get error information:

try
{
    var x = 1 + y;
    console.log(t);
}
catch(e)
{
    console.error("Error: " + e.name);
    console.error("Error: " + e.message);
    console.error("Error: " + e.stack);
}
finally
{
    console.log("Run finally");
}

You can also throw exceptions using throw:

try
{
    throw 'This is an exception';
}
catch(e)
{
    console.error("Error: " + e);
}
finally
{
    console.log("Run finally");
}

This produces:

 

ABOUT CARL DE SOUZA

Carl de Souza is a developer and architect focusing on Microsoft Dynamics 365, BI, Web, Cloud and Data Science.

carldesouza.comLinkedIn Twitter | YouTube

 

Leave a Reply

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