How to handle exception in JavaScript
Exception handling in JavaScript
In this article we will learn how to implement try-catch
block and exception handling mechanism in JavaScript application. If you are
experience web developer then you might know the feature of JavaScript.
We know that JavaScript is client side programming language
which supports few features of object oriented programming language. So that JavaScript
is called as partially object oriented programming language. Nowadays
JavaScript became smarter and supporting various concept of object oriented
programming with the help of various third party class library. Let’s try to
understand try-catch block in JavaScript.
Try-catch in JavaScript.
Exception handling block in java script is very similar with
normal try-catch block in any programming language. The structure is like below.
Try
{
//Code goes here
}
Catch
{
//Exception handling mechanism goes here
}
Finally
{
//Code to clear resource
}
This is our well know exception handling block. Within try we will place those codes which may
throw exception. Within catch block we have to write code to handle the
exception, like call to another method or show error message to user and within
finally block we will write code to release the resource consumed by program within
try block. In below example we will see how try-catch practically.
Practical implementation
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="JavaScript.aspx.cs" Inherits="WebApplication.JavaScript" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript">
function ExceptionTest() {
try
{
document.write(a);
}
catch(exception)
{
alert("Exception occur");
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<input type="button" value="Click me" onclick="ExceptionTest()" />
</form>
</body>
</html>
Within try block we are trying to print value of variable
“a” which is not defined and the error will handle by catch block.
Here is sample output.

We can implement finally block which will execute after the
execution of catch block. Have a look on below example.
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript">
function ExceptionTest() {
try
{
document.write(a);
}
catch(exception)
{
alert(exception);
}
finally {
alert("Finally Executed");
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<input type="button" value="Click me" onclick="ExceptionTest()" />
</form>
</body>
</html>
Finally block will execute after catch block.

Conclusion:-
In this example we have learned how to handle exception
JavaScript application. Hope you have understood the concept.