Consider the following code:
if (window.addEventListener) {
window.addEventListener('load', someFunction, false);
} else if (window.attachEvent) {
window.attachEvent('onload', someFunction);
}
function someFunction() {
alert('Execute!');
}
This works in Chrome, FireFox, IE. I get the alert "execute!". However, if I wrap this in a try-catch block like this:
try{
if (window.addEventListener) {
window.addEventListener('load', someFunction, false);
} else if (window.attachEvent) {
window.attachEvent('onload', someFunction);
}
function someFunction() {
alert('Execute!');
}
}catch(e){
alert(e.message);
}
Then in FireFox I get "someFunction is not defined". I get "execute" in the other browsers.
Can someone explain why this is so? I've spent a day scouring the Internet for any resource that could remotely explain this.
Let's assume I don't have any control of the code inside the try block but I want to trap any potential errors so that code that falls below still gets executed. I was thinking the try-catch block would be the solution but since it doesn't work in this scenario with FireFox, is there an alternative?