Tutorials

Learn web design and programming with our free video and text tutorials.

Javascript Try and Catch Tutorial

Javascript allows you to test a block of code for errors using the "try" and "catch" keywords. The try keyword is followed by a block of code that is enclosed within curly braces, followed by the catch keyword which is followed by a block of code that is executed if an error occurs.

The javascript below shows you how to use the try and catch keywords to check for errors.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>WebDevelopmentTutorials.com</title>

</head>
<body>

<script type="text/javascript" language="javascript">

<!--
try
{
document.write("This is a test $" + myBankBalance);
}
catch(err)
{
document.write("An error has occurred.");
}
//-->

</script>

</body>
</html>

The javascript above contains an error in the try statement and results in the output below.