JavaScript try/catch/finally Statement

This example has a typo in the try block. Alert is misspelled

Definition and Usage

When an error occurs, JavaScript will stop and generate an error message.

Note

The technical term for this is is: JavaScript throws an exception.

JavaScript creates an Error object with two properties: name and message.

The try...catch...finally statements combo handles errors without stopping JavaScript.

The try statement defines the code block to run (to try).

The catch statement defines a code block to handle any error.

The finally statement defines a code block to run regardless of the result.

The throw statement defines a custom error.

Both catch and finally are optional, but you must use one of them.

Note

Using throw with try and catch, lets you control program flow and generate custom error messages.

See Also:

The JavaScript throw

JavaScript Error Object

JavaScript Errors Tutorial

Syntax

try {
  tryCode - Code block to run
}
catch(err) {
  catchCode - Code block to handle errors
}
finally {
  finallyCode - Code block to be executed regardless of the try result
}

Parameters

Parameter Description
tryCode Required.
Code block to be tested while executing.
err A local reference to the error object.
catchCode Optional.
Code block to execute if an error occurs.
finallyCode Optional.
Code block to execute regardless of the try result

More Examples

This example examines input.

If the value is wrong, an exception (err) is thrown:

<p>Please input a number between 5 and 10:</p>

<input id="demo" type="text">
<button type="button" onclick="myFunction()">Test Input</button>
<p id="message"></p>

<script>
function myFunction() {
  const message = document.getElementById("message");
  message.innerHTML = "";
  let x = document.getElementById("demo").value;
  try {
    if(x == "") throw "is Empty";
    if(isNaN(x)) throw "not a number";
    if(x > 10) throw "too high";
    if(x < 5) throw "too low";
  }
  catch(err) {
    message.innerHTML = "Input " + err;
  }
}
</script>

The finally statement executes code, after regardless of the try result:

function myFunction()
  const message = document.getElementById("message");
  message.innerHTML = "";
  let x = document.getElementById("demo").value;
  try {
    if(x == "") throw "Empty";
    if(isNaN(x)) throw "Not a number";
    if(x > 10) throw "Too high";
    if(x < 5) throw "Too low";
  }
  catch(err) {
    message.innerHTML = "Error: " + err + ".";
  }
  finally {
    document.getElementById("demo").value = "";
  }
}

Browser Support

try...catch is an ECMAScript3 (ES3) feature.

ES3 (JavaScript 1999) is fully supported in all browsers:

Chrome IE Edge Firefox Safari Opera
Yes Yes Yes Yes Yes Yes