function connectTo(url) {
var xhr = new XMLHttpRequest();
xhr.open("GET", url, false);
xhr.onreadystatechange = function () {
if (xhr.readyState == xhr.DONE) {
throw "Troubles.";
}
};
xhr.send();
}
try {
connectTo("http://www.google.com");
} catch (e) {
console.log('Exception happend.');
}
也许“catch”部分将执行(在控制台中显示消息),但异常保持未捕获状态(=在控制台中显示“Uncaught Troubles”。)。 为什么呢?
答案 0 :(得分:9)
投掷不会像这样回调。传入错误处理回调并手动处理。
让我来说明你的堆栈痕迹
onreadystatechange函数和connectTo函数之间没有堆栈跟踪连接。所以当你抛出一个错误时,它永远不会冒泡到connectTo周围的try catch块。
firefox正在做的是"Oh you did something that doesn't work. let me fix that for you and do what you think it does"
function connectTo(url, err) {
var xhr = new XMLHttpRequest();
xhr.open("GET", url, false);
xhr.onreadystatechange = function () {
if (xhr.readyState == xhr.DONE) {
err.call(this, new Error("troubles"));
}
};
xhr.send();
}
connectTo("http://www.google.com", function(e) {
console.log(e);
});