我想在browsermob中测试某些输入字段是否工作。我试图使用我以前从未使用过的try ... catch语句。我知道表单是:JavaScript的尝试... catch语句的工作方式
try {
//some code
} catch(){
//some error code
};
究竟应该在catch语句之后的圆括号里放什么? 当我尝试使用该语句时,它会通过catch语句运行所有内容,而不管它是否为错误。我究竟做错了什么?
我想在browsermob中测试某些输入字段是否工作。我试图使用我以前从未使用过的try ... catch语句。我知道表单是:JavaScript的尝试... catch语句的工作方式
try {
//some code
} catch(){
//some error code
};
究竟应该在catch语句之后的圆括号里放什么? 当我尝试使用该语句时,它会通过catch语句运行所有内容,而不管它是否为错误。我究竟做错了什么?
查看“try...catch
statement” guide on MDN。
简而言之,try/catch用于处理异常(使用throw
语句“抛出”)。对于try/catch语句的语法是:
try {
// Code
} catch (varName) { // Optional
// If exception thrown in try block,
// execute this block
} finally { // Optional
// Execute this block after
// try or after catch clause
// (i.e. this is *always* called)
}
varName
只提供给了catch
块的范围。它引用抛出的异常对象(可以是任何类型的对象,例如String
,但通常是Error
object)。
try catch语句用于检测在try
-block内引发的异常/错误。在catch块中,您可以对这种异常行为做出反应并尝试解决它或进入安全状态。
你有差不多吧声明:
try {
// code that may fail with error/exception
} catch (e) { // e represents the exception/error object
// react
}
请看下面的例子:
try {
var x = parseInt("xxx");
if(isNaN(x)){
throw new Error("Not a number");
}
} catch (e) { // e represents the exception/error object
alert(e);
}
try {
// some code
if(!condition){
throw new Error("Something went wrong!");
}
} catch (e) { // e represents the exception/error object
alert(e);
}
所以你不一定需要有最后的声明? – chromedude 2010-08-14 18:15:28
yes终于是声明的一个可选部分,它保证它内部的代码被执行,无论是否存在异常。 – 2010-08-20 11:58:05
内尝试{...}的东西是要执行什么。 catch(){...}中的东西是你想要执行的,如果你从try {...}中执行的任何东西得到任何javascript错误0127 try {...}块中的javascript错误。你可以找出错误是由例如这样的:
try {
// do something
} catch (err) {
alert(err);
}
谢谢,这就是我正在试图找出 – chromedude 2010-08-14 18:12:27
很可能抛出一个异常,进入try { }
代码,当有异常抛出要运行的代码,进入catch() { }
。在catch()中,您可以指定要捕获哪些异常,以及在哪个自动变量中放置它。无论是否抛出异常,总是运行 finally { }
。
据ECMAScript
规格,
try {
// Code
} catch (varName) { // optional if 'finally' block is present.
if (condition) { // eg. (varName instanceof URIError)
// Condition (Type) specific error handling
}
else {
// Generic error handling
}
} finally { // Optional if 'catch' block is present.
// Execute this block after
// try or after catch clause
// (i.e. this is *always* called)
}
谢谢,我觉得这是现在做更有意义。那么catch之后的括号是否包含错误的变量? – chromedude 2010-08-14 18:07:04
@srmorriso,是;看我的编辑。 – strager 2010-08-14 18:09:26
好的,谢谢。现在有意义 – chromedude 2010-08-14 18:14:21