一、try catch语法
try…catch…finally…语法中除了try以外,catch和finally都是可选的(两者必须要有一个),也就是说try…catch…finally…语法有以下三种形式。
形式1
try{ //do something } catch(e){ //somecode } finally{ //do something }
形式2
try{ //do something } catch(e){ //somecode }
形式3
try{ //do something } finally{ //do something }
二、try catch用法
避免在循环中使用try-catch-finally
var $myObj = ['foo', 'bar'], i;
//不好的用法 for (i = 0, len = $myObj.length; i <len; i++) { try { // do something that throws an exception } catch (e) { // handle exception } }
//好的用法 try { for (i = 0, len = $myObj.length; i <len; i++) { // do something that throws an exception } } catch (e) { window.location.href = "http://stackoverflow.com/search?q=[js]+" + e.message; }