by Edward
06 October 2009 06:16
Like any OOP (Object Oriented Programming), exception handling is also available in Javascript. The try/catch block in JavaScript is very much similar to the regular C# try/catch block, but you cannot handle the errors server side.
In the catch block you will get the object containing type and description of the exception, which you can then handle or write out to the screen, to see the error. You can also use the finally block in the same way as you use it in C#.
Here is a simple example:
window.onload = function()
{
try
{
var x = 10;
var calcvalue = x / y;
}
catch(err)
{
document.write("Error has been thrown:" + err.name + "<br /> Message: " + err.message + "<br />");
}
finally
{
alert('This is the finally block');
}
}