【发布时间】:2014-08-30 05:26:05
【问题描述】:
这是关于将异常处理逻辑包装在某种类中。在编写 c++ 时 代码,很多时候我们需要根据客户端抛出的异常捕获许多类型/变体。这导致我们在 catch() 子句中(多次)编写类似类型的代码。
在下面的示例中,我编写了函数(),它可以以多种可能的形式抛出异常。
我想知道是否可以以类的形式编写/包装这样的逻辑,以便最终用户不得不一次编写类似类型的代码? 有什么意义吗?
#include<vector>
#include<string>
#include<exception>
#include<iostream>
// this function can throw std::exception, std::string, int or unhandled
void function() {
std::vector<int> x{1,2,3,4,5};
auto val = x.at(x.size()); //throw out-of-range error
}
int main() {
try { function(); }
catch(std::exception& e) { std::cout<<e.what()<<std::endl; }
catch(std::string& msg) { std::cout<<msg<<std::endl; }
catch(int i) { std::cout<<i<<std::endl; }
catch(...) { std::cout<<"Unhandled Exception"<<std::endl; }
return 0;
}
到目前为止我是这样想的,下面是伪逻辑。
class exceptionwrapper{ exceptionwrapper(function pointer* fp) { // functions which would be executing inside try } ~exceptionwrapper() { // all catch() clause can be written over here // or some other member function of this class } };
这个类的对象可以通过这种方式在main()中实例化。
int main() {
exceptionwrapper obj(function);
//here execptionwrapper destructor would take care about calling all type of catch
}
【问题讨论】:
标签: c++ c++11 exception-handling raii