Skip to content
Advertisement

How do try…catch statements really work in IE?

I have a foreach() loop in this function and by searching the internet I know, that for each loop doesn’t work in IE. To save my time I simply put a: try {} catch {} around it, but IE still reminds me, by function call, that there is an error.

Why does IE 11 work ? Code:

Code:

function classAndIdSpy() {

var req = new XMLHttpRequest();
var x = document.getElementsByClassName("spy");
var page_you_on = window.location.href.split("/");
var json56 = '{ "div_ids_classes" : [{"PAGE":"'+page_you_on[page_you_on.length-1]+'"},';

try {
   // Block of code to try. 
for(var xy of x) { 

json56 += '{"SPY_ID":"'+xy.id+'","CLASS":"'+xy.parentNode.className+'","ID":"'+xy.parentNode.id +'"}';

json56 += (x.length-1 > [].indexOf.call(x, xy)) ? ',' : '';

}
json56 += ']}';

req.open('POST', '../admin/id_class_colect.php', true);
req.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
req.send("json2="+json56);

var status;
req.onreadystatechange = function() {//Call a function when the state changes.
    if(req.readyState == 4 && req.status == 200) {
        status = req.responseText;        
        console.log("Send ajax. Colected Id and Class information of content DIVs into database. Status:"+status);         
    }}
}
catch(err) {
      console.log("Your browser doesn't support ID and Class information of content DIV into database. Please use another browser.");
       return false;   
   } 
} //End of ClassAndIDspy

I get the following error in the console: SCRIPT1004: Expected ‘;’ (The function works fine in Firefox, and I don’t think there is a semicolon missing)

And, this is the part I would like Internet Exporer to ignore: Code:

for(var xy of x) { 

json56 += '{"SPY_ID":"'+xy.id+'","CLASS":"'+xy.parentNode.className+'","ID":"'+xy.parentNode.id +'"}';

json56 += (x.length-1 > [].indexOf.call(x, xy)) ? ',' : '';

}

Thank you for any help !

Advertisement

Answer

You appear to have misunderstood the point of trycatch.

try and catch are used to handle exceptions that arise when your JavaScript code runs. Your code doesn’t get to run in IE because it fails to compile. There’s nothing try and catch can do about compilation failures.

As I see it, your options are:

  • Use Babel or some other transpiler to convert modern JS code to JS code that will run in IE.
  • Use a ‘plain’ for loop instead of your for (xy of x) loop. Doing so does not involve a lot of effort, and as I noted in a comment your for loop is using the index of the element within the array anyway.

I strongly recommend you give up on your idea of getting IE to ignore a block of code.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement