This example has a typo in the try block. Alert is misspelled.
The catch block catches the error and executes the code to handle it:
<p id="demo"></p>
<script>
try {
adddlert("Welcome guest!");
}
catch(err) {
document.getElementById("demo").innerHTML = err.message;
}
</script>
Try it Yourself »
More examples below.
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.
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
}
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>
Try it Yourself »
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 it Yourself »
try...catch
is an ECMAScript3 (ES3) feature.
ES3 (JavaScript 1999) is fully supported in all browsers:
Chrome | Edge | Firefox | Safari | Opera | IE |
Yes | Yes | Yes | Yes | Yes | Yes |
截取页面反馈部分,让我们更快修复内容!也可以直接跳过填写反馈内容!