w3resource

JavaScript: try...catch statement

Description

The try...catch statement marks a block of statements to try and a block of statement to catch errors if an exception is thrown.

Syntax

try
{
// statements
}
catch (error)
{
// statements

The try block contains one or more statements enclosed by brackets. The catch block also contains one or more statements enclosed by brackets that specify what to do if an exception is thrown in the try block. If any statement within the try block throws an exception, control immediately shifts to the catch block. If no exception is thrown in the try block, the catch block is skipped.

Example: without a Try... Catch statement

Code

<script type="text/javascript">
alertt("We are learning Try..Catch statement");
</script>

The above example contains a script which should write a statement "We are learning Try..Catch statement in a web page. But the code produces an error as document.write() is mistyped documentt.write().

View the example in the browser

Let's try the above example with a Try...Catch statement.

Example: with a Try... Catch statement

Code

<script type="text/javascript">
try
{
alert("We are learning Try..Catch statement");
}
catch(err)
{
alert("An error has occurred....Click on OK button to continue.");
}
</script>

The above code produces an error as alert() is mistyped alertt(). However this time the code will hide the error as catch block catches the error and display an user friendly message.

View the example in the browser

Previous: JavaScript: for in Statement
Next: JavaScript: throw statement

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.