Ang JavaScript throw statement
- 上一页 switch
- 下一页 try...catch
- 返回上一层 JavaScript Statement Reference Manual
Paglilinaw at Paggamit
Ang throw na statement ay nagtataos (nagbibigay) ng error.
Kapag may error, ang JavaScript ay karaniwang sumasara at gumagawa ng mensahe ng error.
Ang teknikal na termino nito ay: ang JavaScript ay magsisitaos (throw) ng error.
Ang throw na statement ay nagbibigay sa iyo ng kapangyarihan na gumawa ng sariling error.
其技术术语是:抛出异常(exception)。
异常可以是 JavaScript 字符串、数字、布尔值或对象:
throw "Too big"; // 抛出文本 throw 500; // 抛出数字
如果将 throw 与 try 和 catch 一起使用,则可以控制程序流并生成自定义错误消息。
有关 JavaScript 错误的更多知识,请学习我们的 JavaScript 错误教程。
实例
本例例检查输入。如果值是错的,则抛出异常 (err)。
catch 语句捕获异常 (err) 并显示自定义错误消息:
<!DOCTYPE html> <html> <body> <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() { var message, x; message = document.getElementById("message"); message.innerHTML = ""; 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> </body> </html>
语法
throw expression;
参数值
参数 | 描述 |
---|---|
expression | 必需的。要抛出的异常。可以是字符串、数字、布尔值或对象。 |
技术细节
JavaScript 版本: | ECMAScript 3 |
---|
浏览器支持
语句 | Chrome | IE | Firefox | Safari | Opera |
---|---|---|---|---|---|
throw | 支持 | 支持 | 支持 | 支持 | 支持 |
- 上一页 switch
- 下一页 try...catch
- 返回上一层 JavaScript Statement Reference Manual