gpt4 book ai didi

c++ - 是否可以在不同的类中编写/包装异常处理组件(try、catch)?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:07:12 24 4
gpt4 key购买 nike

这是关于将异常处理逻辑包装在某种类中。在写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
}

};

这样可以在ma​​in()中实例化该类的对象。

int main() {
exceptionwrapper obj(function);
//here execptionwrapper destructor would take care about calling all type of catch
}

最佳答案

可以使用 std::exception_ptr :

Live demo link.

#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); ,希望此函数仅当有正在处理的事件异常时被调用(否则您的程序将被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();
}

Yet another live demo link.

关于c++ - 是否可以在不同的类中编写/包装异常处理组件(try、catch)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25579323/

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