Intro
Inside of this jQuery(document).ready() function, inside the anonymous function, I am throwing an error which gets caught inside of the second catch block. Then I am throwing an error inside of that catch block AND trying to catch it outside in the first try catch block.
Questions.
- Is this possible? BROWSER CONSOLE says “UNCAUGHT.”
- If so, how is it possible?
- Any other info would be greatly appreciated – Trying to wrap my head around this.
try { // bind to ready jQuery(document).ready(function () { try { throw Error("Can this be caught outside of this jquery callback?"); _this.initialize(); } catch(e) { console.log(e.message + ' Caught inside callback'); throw Error(e.message + ' Not caught outside'); } }); } catch(e) { //NEVER gets executed. console.log(e.message); }
Advertisement
Answer
Event handlers for $(document).ready
are executed asynchronously to the code that registers them – if the page is still loading, when the registration occurs. Your function() { ... throw ... }
executes outside the outer try/catch
block. What you are asking is not possible.
Explanation of behaviour observed by @RickHitchcock in https://jsfiddle.net/a3vttpk6/ (see first comment to the question)
If in Rick’s fiddle you click on Javascript settings button, you will see that “LOAD TYPE” setting is “onLoad”. This means that the whole js code in this window is wrapped in window.onload = function() { ... }
. The consequence of this is – the immediate execution of $(document).ready
handlers, because the page has already loaded. If you choose “no wrap” setting – you will see the behaviour described in the question.