可能重复:
在C++中通过指针捕获异常
我总是通过价值来捕捉异常.例如
try{
...
}
catch(CustomException e){
...
}
Run Code Online (Sandbox Code Playgroud)
但我遇到了一些相反的代码catch(CustomException &e).这是a)罚款b)错误c)灰色区域?
是否可以使用文件打开的异常作为使用的替代方法.is_open()?
例如:
ifstream input;
try{
input.open("somefile.txt");
}catch(someException){
//Catch exception here
}
Run Code Online (Sandbox Code Playgroud)
如果是这样,那是什么类型的someException?
默认的catch语句如何catch(...) {}通过值或引用捕获异常?
其次,默认抛出如何throw;通过值或引用抛出异常?
我对异常处理的理解非常有限.虽然我发现很容易抛出异常(或者我可以将它打包expected<T>用于以后的消费),但我对如何处理异常几乎一无所知.
目前我的知识仅限于
清理我自己的资源并重新抛出要在适当位置处理的异常.例如
ptr p = alloc.allocate(n);
try
{
uninitialized_copy(first,last,p);//atomic granularity, all or none
}
catch(...)
{
alloc.deallocate(p,n);
throw;
}
Run Code Online (Sandbox Code Playgroud)但我想,这可以在一个RAII模式中等效地转换为
alloc_guard<ptr> p{alloc.allocate(n)};
uninitialized_copy(first,last,p.get());
p.commit();
Run Code Online (Sandbox Code Playgroud)
在顶层捕获异常,撰写并打印一条好消息并退出.eg
int main(int argc,char** argv)
{
try
{
app_t the_app(argc,argv);
the_app.run();
}
catch(std::runtime_error& e)
{
//instead of what, I can also compose the mesage here based on locale.
std::cout<<e.what()<<std::endl;
}
}
Run Code Online (Sandbox Code Playgroud)所以,我所做的就是处于顶级功能,例如main捕获异常并打印相应的消息并关闭.
在使用各种外部库作为实现的后端实现具有一组良好API的库时,我意识到第三方库异常是我的API规范的一部分,因为它们跨越我的库边界并落在用户代码中!
因此,我的库API泄露了我用于用户代码的外部库(并且每个库都有自己的异常层次结构)的所有异常.
这导致了我的问题,当我发现任何异常时可以做些什么?
进一步来说,
mpl::map)吗?file_not_found或者disk_error,用另一个文件重新运行该函数)?谢谢
我有一个自定义异常是
class RenterLimitException : public std::exception
{
public:
const char* what();
};
Run Code Online (Sandbox Code Playgroud)
覆盖 what() 的正确方法是什么?现在,我在头文件中创建了这个自定义,并希望覆盖我的 cpp 文件中的 what()。我的功能定义如下:
const char* RenterLimitException::what(){
return "No available copies.";
}
Run Code Online (Sandbox Code Playgroud)
但是,当我使用我的 try/catch 块时,它不会打印我给函数 what() 的消息,而是打印std::exception
我的 try/catch 块是这样的:
try{
if (something){
throw RenterLimitException();}
}
catch(std::exception& myCustomException){
std::cout << myCustomException.what() << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
是因为我的 try/catch 块还是我的what()功能?提前致谢