How to do Error Handling in Javascript

Error handling in Javascript uses the same style that C/C++ and C# has, in that it uses the Try...Catch...Finally construct.

try
    {
        var elem = document.getElementById('para');
        elem.style.color = newColor;
        throw 'Error';
    }
catch (err)
    {
        alert(err);
    }
finally
    {
        alert('Finally finished');
    }

In the above, the first instruction in the try will cause an error because there is no element on the page called para. Without the error handling, the script will stop. Copy the elem statement outside the try statement and re-run, the throw will not happen, the script will end. In the browser console window, an error will be written. The message that is written is the same that will be in err value when the catch occurs.

With the document command inside the try and you run, the alert box will occur saying that it cannot read the properties of null. When the box is closed, another box will appear saying "Finally finished.". If you put a line after the throw statement, it will not be executed.

This may be a short document but there really isn't that much to write about it. The value in the err variable will be the error message describing the issue.

Tags - Javascript

Last Modified : June 2023


About... / Contact.. / Cookie...