try…catch 网站建设定制开发语句是什么?
try…catch 网站建设定制开发可以测试代码中的错误。try 网站建设定制开发部分包含需要运行的代码,而 catch 网站建设定制开发部分包含错误发生时运行的代码。
try…catch语法
try { //在此运行代码}catch(err){ //在此处理错误}运行流程:try{...}包含块中的代码有错误,则运行catch(err){...}内的代码,否则不运行catch(err){...}内的代码。
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
try…catch案例
message(){ var txt=""; try { adddlert("Welcome guest!"); } catch(err) { txt="本页有一个错误。\"; txt+="错误描述:" + err.message + "\"; txt+="点击确定继续。\"; alert(txt); } }
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
try…catch…finally 语句
提供了一种方法来处理可能发生在给定代码块中的某些或全部错误,同时仍保持代码的运行。如果发生了程序员没有处理的错误,JS只给用户提供它的普通错误信息,就好象没有错误处理一样。
try…catch…finally 语法
try { tryStatements} catch(exception){ catchStatements} finally { finallyStatements} 参数 tryStatement 必选项。可能发生错误的语句。 exception 必选项。任何变量名。exception 的初始化值是扔出的错误的值。 catchStatement 可选项。处理在相关联的 tryStatement 中发生的错误的语句。 finallyStatements 可选项。在所有其他过程发生之后无条件执行的语句
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
try…catch…finally 案例
myFunction() { var message, x; message = document.getElementById("p01"); message.innerHTML = ""; x = document.getElementById("demo").value; try { if(x == "") throw "值是空的"; if(isNaN(x)) throw "值不是一个数字"; x = Number(x); if(x > 10) throw "太大"; if(x < 5) throw "太小"; } catch(err) { message.innerHTML = "错误: " + err + "."; } finally { document.getElementById("demo").value = ""; }}程序执行过程1. catch(err)语句捕获到这个异常通过err.name打印了错误类型,err.message打印了错误的详细信息. 2. finally类似于java的finally,不论之前的 try 和 catch 中是否产生异常都会执行该代码块.
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
Throw 语法
Throw 语句
(1). 允许我们创建自定义错误。
(2). 正确的技术术语是:创建或抛出异常(exception)。
(3). 如果把 throw 与 try 和 catch 一起使用,那么您能够控制程序流,并生成自定义的错误消息。
(4). throw exception 异常可以是 JavaScript 字符串、数字、逻辑值或对象。
myFunction() { var message, x; message = document.getElementById("message"); message.innerHTML = ""; x = document.getElementById("demo").value; try { if(x == "") throw "值为空"; if(isNaN(x)) throw "不是数字"; x = Number(x); if(x < 5) throw "太小"; if(x > 10) throw "太大"; } catch(err) { message.innerHTML = "错误: " + err; }}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
请注意,如果 getElementById 函数出错,上面的例子也会抛出一个错误。
现总结Error.name的六种值对应的信息:
EvalError:eval()的使用与定义不一致
RangeError:数值越界
ReferenceError:非法或不能识别的引用数值
SyntaxError:发生语法解析错误
TypeError:操作数类型错误
URIError:URI处理函数使用不当