在我所了解的语言中(包括C++,Java,Javascript,Python,PHP等),我总是看到有
例如,考虑下面的代码:
我想象这是一个替代选择。
(我对为什么这个方法无法适用于C++和Java等语言的答案在下面发布,但我没有针对动态语言的答案。)
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等语言的答案在下面发布,但我没有针对动态语言的答案。)
try
代码块,因为你试图做一些需要比当前范围更深的语义要求。如果它足够大以影响清晰度,你可以评论该代码块,但它不必变得不清晰。我正在询问的是,在不需要语义上所需的更深范围的情况下(例如整个函数的catch),使更深层次的范围变为可选的问题。 - leewzif
语句并用while/break
替换它。有很多事情你可以做。但是,计算机语言应该尽可能易于阅读和理解,让人们为了查找catch语句的开头大括号而费力不应该是朝着这个方向取得进展的。 - Hot Licks