处理自定义例外的课程

class for handling custom exception

本文关键字:自定义 处理      更新时间:2023-10-16

我想创建一个符合std ::功能并允许处理指定异常的类,但我不确定是否可能。

这是伪草稿:

//exception types
template<class... Args>
class CustomExceptionHandler
{
public:
    CustomExceptionHandler(std::function<void()> clb): clb_(std::move(clb)){}
    void ExecuteCallback()
    {
        try
        {
            clb_();
        }
        /*catch specified exception types*/
    }
private:
    std::function<void()> clb_;
};
//usage
CustomExceptionHandler<std::out_of_range, std::overflow_error> handler(clb);
handler.ExecuteCallback();

我不知道如何使用variadic模板来获取异常类型并以后使用它。有可能吗?

我猜元组可能会有所帮助。

可能!我做了一个解决方案(您可以在此处运行),将异常类型的参数包扩展到一系列递归功能调用中,每个功能都尝试捕获一种类型的异常。最内向的递归电话然后调用回调。

namespace detail {    
    template<typename First>
    void catcher(std::function<void()>& clb){
        try {
            clb(); // invoke the callback directly
        } catch (const First& e){
            // TODO: handle error as needed
            std::cout << "Caught an exception with type "" << typeid(e).name();
            std::cout << "" and message "" << e.what() << ""n";
        }
    }
    
    template<typename First, typename Second, typename... Rest>
    void catcher(std::function<void()>& clb){
        try {
            catcher<Second, Rest...>(clb); // invoke the callback inside of other handlers
        } catch (const First& e){
            // TODO: handle error as needed
            std::cout << "Caught an exception with type "" << typeid(e).name();
            std::cout << "" and message "" << e.what() << ""n";
        }
    }
}
template<class... Args>
class CustomExceptionHandler
{
public:
    CustomExceptionHandler(std::function<void()> clb): clb_(std::move(clb)){}
    void ExecuteCallback()
    {
        detail::catcher<Args...>(clb_);
    }
private:
    std::function<void()> clb_;
};
int main(){
    
    std::function<void()> clb = [](){
        std::cout << "I'm gonna barf!n";
        throw std::out_of_range("Yuck");
        //throw std::overflow_error("Ewww");
    };
    
    CustomExceptionHandler<std::out_of_range, std::overflow_error> handler(clb);
    handler.ExecuteCallback();
    
    return 0;
}

输出:

I'm gonna barf!

Caught an exception with type "St12out_of_range" and message "Yuck"

template<typename E0, typename ... En>
class ExceptionCatcher
{
public:
    template<typename F>
    void doit(F&& f)
    {
        try 
        {
            ExceptionCatcher<En...> catcher;
            catcher.doit(std::forward<F>(f));
        }
        catch(const E0 &)
        {
            std::cout << __PRETTY_FUNCTION__ << 'n';
        }
    }
};
template<typename E0>
class ExceptionCatcher<E0>
{
public:
    template<typename F>
    void doit(F&& f)
    {
        try 
        {
            f();
        }
        catch(const E0 &)
        {
            std::cout << __PRETTY_FUNCTION__ << 'n';
        }
    }
};

https://wandbox.org/permlink/dauqtb9rwvmzt4b6