Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What if I use "throw" in "catch"?

Tags:

javascript

function f(){
    try{
        if (/*some codes*/) throw false;
        return true;
    }
    catch(x){
        if (x===false) return false;
        throw x;
    }
}

Here,what does "throw x" mean? It seems codes in "catch" won't run twice.

like image 656
SPiCa Avatar asked Feb 27 '14 13:02

SPiCa


3 Answers

If you had something like:

try {
    try {
        //something
    } catch(x) {
        throw x;
    }
} catch(x) {
    //handle it
}

The throw in the inner catch would cause the outer catch to execute

like image 130
neelsg Avatar answered Oct 25 '22 08:10

neelsg


It means it throws the exception to the calling function, which will execute its catch block in case there is one defined.

For example, in the below code, you log the exception in the callthis() function, but you would like the calling function (init()) to decide how to handle it. Hence you re-throw the exception, which gets bubbled up.

window.onload = init();
function init(){
    try {
        callthis();
    } catch(e) {
        alert('init - calling function');
    }
}

function callthis(){
    try {
        var x = null.split(','); //inducing an error
    } catch(e){
        alert('callthis - called function');
        throw e;
    }
}

Fiddle

like image 38
rakhi4110 Avatar answered Oct 25 '22 09:10

rakhi4110


When you have a try/catch block in Javascript, the catch block will take any error that can happen in try block. The keyword throw is used to throw a error to the superior scope (who call the function for sample) passing the error on it (exception) that will be taken by the catch block. In the catch you can take as a first argument the exception. In your code, you get a error the throw using throw x where x is the exception. The caller will get the x as a argument on the catch block.

function K()
{
   try
   {
      f();
   }
   catch(ex)
   {
      // handle any exception thrown by f();
   }    
}

If you or the runtime throw an error on catch block, it will be passed to superior scope, in this case, the scope who called K function.

like image 28
Felipe Oriani Avatar answered Oct 25 '22 08:10

Felipe Oriani