我想知道程序员何时使用函数try块.什么时候有用?
void f(int i)
try
{
if ( i < 0 )
throw "less than zero";
std::cout << "greater than zero" << std::endl;
}
catch(const char* e)
{
std::cout << e << std::endl;
}
int main() {
f(1);
f(-1);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出:(在ideone处)
greater than zero
less than zero
Run Code Online (Sandbox Code Playgroud)
编辑:因为有些人可能认为函数定义的语法不正确(因为语法看起来不熟悉),我要说它不是不正确的.它叫做function-try-block.参见C++标准中的§8.4/ 1 [dcl.fct.def].
您可能知道这样的情况,您只想分配一个const带有表达式的()变量,该表达式可能会失败(抛出)(例如container.at()),这会迫使您编写样板代码:
void foo(const string &key) {
auto it = data_store.find(key);
if (it == data_store.end()) {
return;
}
const auto & element = it->second;
...
go on with `element`...
...
}
Run Code Online (Sandbox Code Playgroud)
在Python中,您可以编写如下代码:
def foo(name):
try:
element = data_store[key]
except KeyError:
return
..
go on with `element`
..
Run Code Online (Sandbox Code Playgroud)
..因为你没有引入那些无用的额外it只是为了检查存在而没有噪音.
如果C++ try不会引入变量作用域,你可以使用at():
void foo(const string &key) {
try {
const auto & element = data_store.at(key);
} catch (const out_of_range &) {
return;
}
... …Run Code Online (Sandbox Code Playgroud)