日期:2014-05-16  浏览次数:20462 次

JavaScript中try catch finally 使用
在IE泄漏中处理是遇到的方法,通过try..catch..finally方式:
function createButton(){
 var obj = document.createElement("button");
 obj.innerHTML="点我!";
 obj.onclick=function(){
   //处理click事件
 }
 obj.onmouseover=function(){
   //处理mouseover事件
 }
try{
  return obj;
 }finally{
   obj = null;//在return 之后才执行,解决了在return后将obj置null问题
 }
} 


错误处理结构:  
   try{   
       tryStatements
   }   
   catch(exception){   
       catchStatements}   
   finally{   
       finallyStatements
   }   

参数:  
   tryStatement    
   必选项。可能发生错误的语句。    
   exception    
   必选项。任何变量名。exception的初始化值是扔出的错误的值。    
   catchStatement    
   可选项。处理在相关联tryStatement中发生的错误的语句。    
   finallyStatements    
   可选项。在所有其他过程发生之后无条件执行的语句。    

说明:     
如果在tryStatements中发生了一个错误,则程序控制被传给catchStatements来处理 ,错误处理发生之后,将会执行finallyStatements中语句。

(function(){
    try{
       console.info('1');
       return 'try begin'   //1
    }catch(e){
       console.info('2');
       return 'try catch'   //2 
    }finally{
       console.info('3');
       return 'try finally' //3
    }
})();

执行上述代码,发现在1返回return前将会执行到finally,如果其中有return那么函数执行返回,否则执行到1处return返回。如果注释掉3将会返回什么呐?

catch中e.name错误类型:
  • 1. EvalError:eval()的使用与定义不一致
  • 2. RangeError:数值越界
  • 3. ReferenceError:非法或不能识别的引用数值
  • 4. SyntaxError:发生语法解析错误
  • 5. TypeError:操作数类型错误
  • 6. URIError:URI处理函数使用不当

参考:
http://xiaolele.iteye.com/blog/679567
http://www.welefen.com/javascript-try-finally.html
http://www.cnblogs.com/silence516/archive/2009/02/20/1394651.html