最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - throwing and catching exception from function - Stack Overflow

programmeradmin3浏览0评论
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 badges
Add a ment  | 

1 Answer 1

Reset to default 9

the 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);
});
发布评论

评论列表(0)

  1. 暂无评论