G++ 自定义异常处理程序
g++ custom exception handler
是否可以为 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;
}
相关文章:
- 与异常处理程序中的操作员<<不匹配
- 数组 C++ 上的异常处理程序
- 视觉 std::矢量无异常:警告 C4530:使用了C++异常处理程序,但未启用展开语义.指定 /EHsc
- 奇怪的消息 (_Base_bitset::_M_do_to_ulong) 从溢出异常处理程序中打印出来
- 处理许多自定义异常的最佳方法是什么
- C++ 中未处理的异常处理程序
- 如何在抛出未处理的自定义异常后调用 what()?
- 如何在 Windows 异常处理程序中设置 MMX 寄存器以模拟不受支持的 3DNow! 说明
- G++ 自定义异常处理程序
- 内部异常处理程序,MessageBox()成功返回IDOK,但从未显示
- 预处理一个自定义文本文件,以使用Boost Spirit删除注释
- 如何从将触发脚本异常处理程序的C++引发异常
- 将 INT3 中断保留给视觉工作室上的应用程序异常处理程序
- 如何在气泡排序中为字符串和双精度实现异常处理程序
- 从硬件异常处理程序引发C++异常.为什么 -fnon-call-exception 没有按预期运行
- 我应该如何编写国际化的异常处理程序
- "Ctrl + F6"的默认处理在自定义 MDI 应用程序中不起作用
- 使用try-Catch异常处理程序和if-else条件检查之间的区别
- 异常处理程序
- 我可以从Qt中的异常处理程序中发出信号吗