Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
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 to insert an item into an array at a specific index (JavaScript)?

What you want is the splice function on the native array object.

arr.splice(index, 0, item); will insert item into arr at the specified index (deleting 0 items first, that is, it's just an insert). In this example we will create an array and add an element to it into index 2:

var arr = [];
arr[0] = "Jani";
arr[1] = "Hege";
arr[2] = "Stale";
arr[3] = "Kai Jim";
arr[4] = "Borge";

console.log(arr.join());
arr.splice(2, 0, "Lene");
console.log(arr.join());

Ref: https://bit.ly/2BXbp04