Skip to content
Advertisement

How to throw an error inside of a call back, and catch it outside

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.

  1. Is this possible? BROWSER CONSOLE says “UNCAUGHT.”
  2. If so, how is it possible?
  3. 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.

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