这是关于将异常处理逻辑包装在某种类中。在写c++的时候
代码中,很多时候我们需要根据客户端抛出的异常来捕获许多类型/变体。这导致我们在 catch() 子句中(多次)编写类似类型的代码。
在下面的示例中,我编写了 function(),它可以以多种可能的形式抛出异常。
我想知道是否可以以类的形式编写/包装此类逻辑,以便最终用户必须立即编写类似类型的代码?它有什么意义或者有什么意义吗?
#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
}
可以使用std::exception_ptr http://www.cplusplus.com/reference/exception/exception_ptr/:
现场演示链接。 http://ideone.com/a51D6D
#include <iostream>
#include <exception>
#include <stdexcept>
void universal_exception_handler(std::exception_ptr e)
{
try
{
std::rethrow_exception(e);
}
catch (const std::logic_error& e)
{
std::cout << "logic_error" << std::endl;
}
catch (const std::runtime_error& e)
{
std::cout << "runtime_error" << std::endl;
}
}
void foo()
{
throw std::logic_error{""};
}
void bar()
{
throw std::runtime_error{""};
}
int main()
{
try
{
foo();
}
catch (...)
{
universal_exception_handler(std::current_exception());
}
try
{
bar();
}
catch (...)
{
universal_exception_handler(std::current_exception());
}
}
您也可以实现这一目标,无需std::exception_ptr
,只需将throw;
代替std::rethrow_exception(e);
,希望这个函数会被调用only if有一个正在处理的异常(否则你的程序将被terminate()'
ed):
void universal_exception_handler()
{
try
{
throw;
}
catch (const std::logic_error& e)
{
std::cout << "logic_error" << std::endl;
}
catch (const std::runtime_error& e)
{
std::cout << "runtime_error" << std::endl;
}
}
try
{
foo();
}
catch (...)
{
universal_exception_handler();
}
另一个现场演示链接。 http://ideone.com/LI4VxD
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)