在這段JavaScript代碼f.init()
控制程序的整個流程:只有一個try-catch塊可以捕獲一些異常嗎?
var f = function() {
return {
init: function(var1) {
try {
f.f1(1)
} catch (e) {
alert(e);
}
try {
f.f2(1)
} catch (e) {
alert(e);
}
// ...
// more try-catch blocks
// ...
},
f1: function() {
throw Error('f1 called');
},
f2: function() {
throw Error('f2 called');
}
};
}();
f.init();
我怎麼能集中所有的異常管理只在一個try-catch塊?類似這樣的:
var f = function() {
return {
init: function(var1) {
f.f1(1) // this cut the control flow if thrown some error
f.f2(1) // so this is not called
},
f1: function() {
throw Error('f1 called');
},
f2: function() {
throw Error('f2 called');
}
};
}();
try {
f.init();
} catch (e) {
alert(e);
}
上面的代碼在拋出一些錯誤後切斷了流程。
你可能要重新審視你的使用異常的......他們似乎並不像他們標誌着特殊(意外)的情況下... – jondavidjohn
你是說你想讓它在發生異常時執行某些操作,但是繼續執行'try'中的其餘代碼? –
@ james-montagne +1即使在f.f1()拋出一些錯誤之後,我也會運行'f.f2()'。但是,正如jondavidjohn +1所說,我沒有很好地使用「例外」概念。 –