我正在尝试在browsermob中测试某些输入字段是否正常工作。我尝试使用try...catch语句,这是我以前从未使用过的。我知道表格格式为:
try {
//some code
} catch (){
//some error code
};
在catch语句的括号中应该放什么? 当我尝试使用该语句时,无论是否出现错误,它都会将所有内容都运行到catch语句中。我做错了什么?
我正在尝试在browsermob中测试某些输入字段是否正常工作。我尝试使用try...catch语句,这是我以前从未使用过的。我知道表格格式为:
try {
//some code
} catch (){
//some error code
};
请参阅MDN上的“try...catch
语句”指南。
简而言之,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
对象)。
try catch语句用于检测在try
块内引发的异常/错误。在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);
}
try {...} 中的内容是您要执行的内容。catch() { ... } 中的内容是如果在 try {...} 中执行任何内容时发生了任何JavaScript错误,您想要执行的内容。
只有在 try {...} 块中出现 JavaScript 错误时,catch {...} 才会执行。您可以通过执行以下操作找出错误:
try {
// do something
} catch (err) {
alert(err);
}
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)
}
可能会抛出异常的代码放在try { }
中,当异常被抛出时需要运行的代码放在catch() { }
中。在catch()中,您可以指定要捕获的异常以及要将其放置在哪个自动变量中。
无论是否抛出异常,finally { }
始终都会运行。
catch
语句运行时,作用域会被扩充,一个包含与标识符同名属性的对象将被添加到作用域链中,如果在作用域中存在另一个具有相同名称的标识符,则它将在catch
块内被简单地遮蔽。 - Christian C. Salvadó