在我看到异常(C++,Java,Javascript,Python,PHP等)的语言中,我总是看到try
或类似的东西来标记catch
的范围。我想知道是否有必要。 try
块有什么设计问题?语言设计(例外):为什么`尝试`?
例如,借此:
try{
try{
do_something_dangerous0();
}catch (SomeProblem p){
handle(p);
}
try{
do_something_dangerous1();
}catch (SomeProblem p){
handle(p);
}
}catch (SomeOtherProblem p){
handle(p);
}
我想象这作为替代。
do_something_dangerous0();
catch (SomeProblem p){
handle(p);
}
do_something_dangerous1();
catch (SomeProblem p){
//catches from only the second unless the first also threw
handle(p);
}
catch (SomeOtherProblem p){
//catches from either, because no other block up there would
handle(p);
}
如果你想避免块醒目“太多”,你可以做一个新的范围:
do_something_dangerous2();
{
do_something_dangerous3();
catch (SomeProblem p){
//does not catch from do_something_dangerous2()
//because if that throws, it won't reach in here
handle(p);
}
}
catch (SomeProblem p){
handle(p);
}
catch (SomeOtherProblem p){
handle(p);
}
(我为什么这不会对语言,如C工作答案++和Java ,至少在下面发布为答案,但我没有针对动态语言的答案。)
在一般情况下,您需要精确定界异常处理范围的开始和结束。人们可以为此使用“孤独”的范围,但它不会真正改变任何事情,并且不太清楚。 –
(我曾经在一个使用BEGIN/NIGEB宏定义异常处理范围的系统上工作,但总体结构几乎与try/catch/finally完全相同,该函数决定语法,而不是其他方法。) –
我是不是用'如果你想避免一个障碍物'太多'......'呢? – leewz