我正在查看隐藏/显示点击内容的网站上的一些代码。
function expando() {
try {
if (document.getElementsByClassName) {
var e = document.getElementsByClassName("expandlink");
t = 0;
} else {
var e = document.querySelectorAll(".expandlink"),
t = 1;
};
if (null != e) {
for (var a = 0; a < e.length; ++a) e[a].onclick = function() {
return OpenClose(this), !1
};
if (1 == t)
for (var a = 0; a < e.length; ++a) {
var n = e[a].href,
r = n.indexOf("#"),
i = n.substr(r + 1),
l = document.getElementById(i);
l.className = l.className + " expandtargetIE8"
}
}
} catch (o) {}
}
function OpenClose(e) {
try {
var t = e.href,
a = t.indexOf("#"),
n = t.substr(a + 1),
r = document.getElementById(n);
r.className = "expandtarget" === r.className ||
"expandtarget expandtargetIE8" === r.className ?
"expandtargeted" : "expandtarget expandtargetIE8",
e.className = "expandlink" === e.className ?
"expandlink expandlinked" : "expandlink"
} catch (i) {}
}
window.onload = function() {
expando()
};
这是JS小提琴。
https://jsfiddle.net/amykirst/3hbxwv1d/
我从未见过JavaScript try ... catch语句。我查看了一些教程,他们都说它们是用于错误测试的。为什么会在这里使用?
看起来捕获实际上并没有做任何事情。
注意:此代码已缩小。我使用在线工具来消除它。
答案 0 :(得分:0)
此处的try..catch
块 用于错误处理。这里使用它来允许代码在出现错误时继续正常执行。
并非所有浏览器都支持document.getElementsByClassName
和document.querySelectorAll
。在不支持的浏览器上,我们会收到以下错误:
未捕获的TypeError:
document.querySelectorAll
不是函数
...进一步的代码执行将停止。
但是,如果此处有try..catch
阻止,则代码根本不会提醒我们有关错误的信息(至少,在o
阻止内检查catch
时)。执行将继续正常进行。它不再是未捕获的错误,它是捕获的错误,它没有完成任何操作。
如果在同一浏览器中,我们要调整上述代码,以便在o
块中记录catch
:
... } catch (o) { console.log(o) }
上面显示的相同信息将显示在控制台上,没有“未捕获”部分:
TypeError:
document.querySelectorAll
不是函数(...)
答案 1 :(得分:0)
实际上try-catch的实际用例很少。
从多功能调用堆栈获取有意义的信息:您可能会在遗留代码中遇到函数f1调用f2而f2调用f3等情况。您可能希望进行一些验证检查,如果验证失败,您可能希望停止流程并显示有意义的错误消息。 (比如说,无效的状态)。为了处理这种情况,我们可以处理自定义异常。
function ValidationError(message) {
this.name = "IocError";
this.message = (message || "Validation/System Error");
}
ValidationError.prototype = Error.prototype;
如果我们看到任何验证错误,我们可以抛出自定义错误,例如函数f3中的throw new ValidationError('Rule is missing...')
。
try {
...
} catch(e) {
if(e instanceof ValidationError) {
infoBox(e.message);
return false;
} else {
//This is not validation error, some other unknown issue has occurred
throw e;
}
}
我们将使用上面的块来捕获函数f1中的异常,如果它是ValidationError类型,我们将显示正确的错误消息。如果它与任何其他类型一样,我们会将其丢弃以备将来的调试用途。