Tech Junkie Blog - Real World Tutorials, Happy Coding!: JavaScript : Error Handling With try/catch/finally

Thursday, November 11, 2021

JavaScript : Error Handling With try/catch/finally

JavaScript error handling is a lot like other languages where you have the try/catch/finally  statement that you can used.  The basic premise is

try
{
     // try some codes here fingers crossed that nothing bad happens
}
catch(ex)
{
     // oops something bad happened, this is where it gets handled or I tell the user
}
finally
{
    // I don't care what happens I am going to execute and get paid
}

Here is the error handling in action:



Let's say type in the following code with the eval( ) function that you know will cause a "Syntax Error".  The catch statement we are going to display the exception in the console. In finally statement we do another evaluation which will execute regardless of whether the try statement was successful.

try
{
    var myvar = "my variable";
    eval(myvar)

}
catch(ex)
{
    console.log("This is the exception " + ex);
}
finally
{
    console.log(eval(1 + 2));
}

Here is the output for the code above:











No comments:

Post a Comment

Search This Blog