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);
});