Skip to content
Advertisement

What if I use “throw” in “catch”?

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.

Advertisement

Answer

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.

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