You are on page 1of 4

JavaScript uses the try catch and finally to handle the exception and it

also used the throw operator to handle the exception. try have the main
code to run and in the catch, give the exception statement all the things
that are related to the exception and finally method which will always
execute unconditionally after the try/catch.

Example 1:
<!DOCTYPE html>
<html>
<head>
<title>Error and Exception handling</title>
<script type="text/javascript">
function sum() {
var a = 12;
var b = 14;
var c = a + b;
try {
alert("Value of a: " + a );
alert ("Value of b: " + b );
alert("Sum of a and b: " + c);
}
catch ( e ) {
alert("Error: " + e.description );
}
finally {
alert("Finally block will always execute!" );
}
}
</script>
</head>

<body>
<p>Click the button to see the result:</p>

<form>
<input type="button" value="button" onclick="sum();" />
</form>

</body>
</html>

Example 2:
<!DOCTYPE html>
<html>
<head>
<script type = "text/javascript">
function myFunc()
{
var a = 100;
try {
alert("Value of variable a is : " + a );
}
catch ( e ) {
alert("Error: " + e.description );
}
finally {
alert("Finally block will always execute!" );
}
}
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type = "button" value = "Click Me" onclick = "myFunc();" />
</form>
</body>
</html>

Example 3:
You can use throw statement to raise your built-in exceptions or your customized
exceptions. Later these exceptions can be captured and you can take an appropriate
action.
The following example is to use a throw statement.
<!DOCTYPE html>
<html>
<head>
<script type = "text/javascript">
function myFunc() {
var a = 100;
var b = 0;
try {
if ( b == 0 ) {
throw( "Divide by zero error." );
}
else {
var c = a / b;
}
}
catch ( e ) {
alert("Error: " + e );
}
}
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type = "button" value = "Click Me" onclick = "myFunc();" />
</form>
</body>
</html>

You might also like