admin管理员组文章数量:1386565
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("");
} catch (e) {
console.log('Exception happend.');
}
Perhaps the "catch" part will execute (in console appears the message), but the exception stays uncatched (= in console appears "Uncaught Troubles."). Why?
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.");
} catch (e) {
console.log('Exception happend.');
}
Perhaps the "catch" part will execute (in console appears the message), but the exception stays uncatched (= in console appears "Uncaught Troubles."). Why?
Share Improve this question asked Feb 6, 2011 at 20:31 Radek SimkoRadek Simko 16.2k18 gold badges72 silver badges110 bronze badges1 Answer
Reset to default 9the throw does not bubble up through a callback like that. Pass in an error handling callback and deal with it manually.
Let me illustrate your stack traces
There is no stacktrace connection between the onreadystatechange function and the connectTo function. So when you throw an error it never bubbles up to the try catch block around connectTo.
What firefox is doing is saying "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.", function(e) {
console.log(e);
});
本文标签: javascriptthrowing and catching exception from functionStack Overflow
版权声明:本文标题:javascript - throwing and catching exception from function - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744550027a2612128.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论