I have a piece of code:
function backgroundReadFile(url, callback) {
var req = new XMLHttpRequest();
req.open("GET", url, true);
req.addEventListener("load", function() {
if (req.status < 400)
callback(req.responseText);
});
req.send(null);
}
try {
backgroundReadFile("example/data.txt", function(text) {
if (text != "expected")
throw new Error("That was unexpected");
});
} catch (e) {
console.log("Hello from the catch block");
}
In my console I get
Error: That was unexpected (line 13)
which is just fine. But, I am told that:
In the code, the exception will not be caught because the call to
backgroundReadFilereturns immediately. Control then leaves thetryblock, and the function it was given won’t be called until later.
The question is: why other errors will not be caught here? When we have, say, connection problems, or the file does not exist? As far as I can see, the callback function won`t execute if
req.addEventListener("load")
is not triggered, for example. But it still does - I still get the same error - Error: That was unexpected (line 13).
What does it mean - "exception will not be caught because the call to backgroundReadFile returns immediately"?
Thank you.