HTML tutorial
CSS3 tutorial
Bootstrap tutorial
JavaScript tutorial
JQuery tutorial
AngularJS tutorial
React tutorial
NodeJS tutorial
PHP tutorial
Python tutorial
Python3 tutorial
Django tutorial
Linux tutorial
Docker tutorial
Ruby tutorial
Java tutorial
C tutorial
C ++ tutorial
Perl tutorial
JSP tutorial
Lua tutorial
Scala tutorial
Go tutorial
ASP.NET tutorial
C # tutorial
This example has a typo in the try block. Alert is misspelled
When an error occurs, JavaScript will stop and generate an error message.
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.
Using throw with try and catch, lets you control program flow and generate custom error messages.
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 |
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 = "";
}
}
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 |