gpt4 book ai didi

c++ - 为什么 catch block 不共享 try block 的范围?

转载 作者:IT老高 更新时间:2023-10-28 23:10:40 24 4
gpt4 key购买 nike

令人惊讶的是,我无法通过谷歌搜索和搜索 SO 找到答案(关于 SO 有很多类似的问题,但与其他语言相关)。

我怀疑答案是。如果是这样,就会有明显的不便,例如

try
{
std::string fname = constructFileName(); // can throw MyException
ofstream f;
f.exceptions(ofstream::failbit | ofstream::badbit);
f.open(fname.c_str());
// ...
}
catch (ofstream::failure &e)
{
cout << "opening file " << fname << " failed\n"; // fname is not in the scope
}
catch (MyException &e)
{
cout << "constructing file name failed\n";
}

如果我的假设是正确的,你会如何处理?通过将 std::string fname; 移出 try,我猜?

我知道范围是由 {} block 定义的,但这似乎是一个合理的情况,嗯,异常(exception)。是不是抛出异常导致对象不能完全构造的原因?

最佳答案

Does catch block share the scope of the try block?

没有。

How do you deal with this? By moving the std::string fname; out of try, I guess?

是的。

I understand that a scope is defined by a {} block, but this seems as a reasonable case for, hmm, exception. Is the reason for that that objects can be not fully constructed if an exception is thrown?

C++ 最不需要的就是更复杂的规则和规则异常(exception)。 :-)

关于c++ - 为什么 catch block 不共享 try block 的范围?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5476454/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com