捕获错误时停止执行javascript

时间:2012-06-27 06:37:20

标签: javascript

我需要一个在catch错误时停止执行javascript的函数。例如如下:

function AA()
{
  try{
    executeScript();
  }catch(e){
    //stop execute javascript
  }
}

function executeScript()
{
   throw 'error';
}
function BB()
{
  //some script
}
AA();
BB(); //don't execute when error happening

有谁知道怎么做?谢谢你的帮助。

3 个答案:

答案 0 :(得分:4)

我认为如果你使用退货应该是可能的:)

function AA()
{
  try{
  }catch(e){
    //stop execute javascript
    return;
  }
  BB(); //don't execute when error happening
}

function BB()
{
  //some script
}

返回就像返回未定义一样。您可以返回更具体的内容,如字符串或其他任何内容,以便在您早日返回时能够提供方便的行为。

答案 1 :(得分:1)

如果希望冗余执行AA代码,也可以使用setTimeout。

function AA()
{
  try{

  }catch(e){
    return;
  }
  BB(); //don't execute when error happening
  setTimeout("AA()",500);
}

function BB()
{
  //some script
}

答案 2 :(得分:0)

有两种方法,

  1. 添加退货声明

    function AA()
    {
      try{
      }catch(e){
        return;
      }
      BB();  
    }
    
    function BB(){   
    }
    
  2. 如果您想在catch调用之前从代码返回,可以添加throw

  3. 功能AA(){

          try{
    
    
        javascript_abort();
    
            }catch(e){
                return;
            }
            BB();  
    }
    
    function BB(){   
            }
    
        function javascript_abort(){
           throw new Error('This is not an error. This is just to abort javascript');
        }