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.



JavaScript: Tips of the Day

How do I redirect to another webpage?

window.location.replace(...) is better than using window.location.href, because replace() does not keep the originating page in the session history, meaning the user won't get stuck in a never-ending back-button fiasco.

If you want to simulate someone clicking on a link, use location.href

If you want to simulate an HTTP redirect, use location.replace.

// similar behavior as an HTTP redirect
window.location.replace("http://stackoverflow.com");

// similar behavior as clicking on a link
window.location.href = "http://stackoverflow.com";

Ref: https://bit.ly/37JdWH8