G++ 自定义异常处理程序

g++ custom exception handler

本文关键字:异常处理程序 自定义 G++      更新时间:2023-10-16

是否可以为 GCC 安装自定义处理程序?

我试图将包装类扔到指针(如 shared_ptr),然后协变捕获它。这实际上是针对我的 GCC 托管C++项目(在 sourceforge 上),但为了以更传统C++友好的方式说明问题,我将在此特定实例中使用 boost::shared_ptr。这就是我想要实现的目标。

void raise()
{
    throw shared_ptr<DerivedException>(new DerivedException);
}
int main()
{
    try
    { 
        raise();
    }
    catch (shared_ptr<Exception> ex)
    {
        // Needs to catch DerivedException too!
    }
}

关于这是否可实现的任何想法?

如果我

理解正确,您可以在没有自定义异常处理程序的情况下在C++中执行所需的操作,但不能使用您正在使用的语法。我可以看到的一个解决方案是将虚拟函数与异常机制相结合。首先,创建一个基类以使捕获变得容易,并为其提供一个接口,以允许轻松重新抛出对象本身及其引用的对象。

struct shared_exception_base_t {
    virtual void raise_ref() = 0;
    virtual void raise_self() = 0;
};
template <class value_t>
class shared_ptr_t : public shared_exception_base_t {
    value_t* ptr_;
public:
    shared_ptr_t(value_t* const p) : ptr_ (p) { }
    void raise_ref()
    {
        throw *ptr_;
    }
    void raise_self()
    {
        throw *this;
    }
};

template <class value_t>
shared_ptr_t<value_t> mk_with_new()
{
    return shared_ptr_t<value_t>(new value_t());
}

然后,您可以使用异常机制进行区分。请注意,try/catch 块必须嵌套。

#include <iostream>
struct file_exception_t { };
struct network_exception_t { };
struct nfs_exception_t : file_exception_t, network_exception_t { };
struct runtime_exception_t { };
void f()
{
    throw mk_with_new<runtime_exception_t>();
}
int
main()
{
    try {
        try {
            f();
        } catch (shared_exception_base_t& x) {
            try {
                x.raise_ref();
            } catch (network_exception_t& fx) {
                std::cerr << "handling network exceptionn"; 
            } catch (file_exception_t& fx) {
                std::cerr << "handling file exceptionn"; 
            } catch (...) {
                x.raise_self();
            }
        }
    } catch (...) { 
        std::cerr << "no idean";
    }
    return 0;
}