JavaScript try/catch not working
Hello, all,
I'm playing around learning stuff, and I've got code in a try/catch that if I intentionally create an error, the catch is not being triggered.
Here's my code:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>CF and JS Dispatch Table Examples</title>
<style>.title{cursor: pointer;}</style>
</head>
<body>
<span id="title1" class="title">One</span> <span id="title2" class="title">Two</span> <span id="default" class="title">Three</span>
<div id="rslts"></div>
<script>
try{
var obj = { // Dispatch table - better (most of the time) than a switch/case
title1: function(){alert('JS: Title One');},
title2: function(){alert('JS: Title Two');},
dflt: function(){alert('JS: Title Three (default)');}
};
var alertIt = function(doWhat){
var thisAction = 'dflt';
if(obj.hasOwnProperty(doWhat)){
thisAction = doWhat;
}
var func = obj[thisAction]; func();
};
var titles = [].slice.call(document.querySelectorAll('.title'));
titles.map(function(x){
x.addEventListener('click',function(){alertIt(x.id);});
});
}catch(e){document.getElementById("rslts").innerHTML += "<br />" + e;}
</script>
</body>
</html>
The above code is correct. However, if I give a different name to "obj" (like rename it "ob"), I should see an error message appear in the div with an ID of "rslts". This is not happening. Instead, I have to open DevTools to Console tab to see "obj doesn't exist".
Can someone please shed light on why the catch isn't being triggered?
V/r,
^ _ ^
