在变量中存储异常的正确方法 [英] correct way to store an exception in a variable

查看:97
本文介绍了在变量中存储异常的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个API,该API内部具有一些用于报告错误的异常。基本结构是它有一个根异常对象,该对象从 std :: exception 继承,然后它将抛出该对象的某些子类。

I have an API which internally has some exceptions for error reporting. The basic structure is that it has a root exception object which inherits from std::exception, then it will throw some subclass of that.

由于捕获在一个库或线程中引发的异常并在另一个库或线程中捕获的异常可能导致未定义的行为(至少Qt抱怨并在许多情况下不允许这样做)。我想将库调用包装在返回状态代码的函数中,如果发生异常,则复制异常对象。

Since catching an exception thrown in one library or thread and catching it in another can lead to undefined behavior (at least Qt complains about it and disallows it in many contexts). I would like to wrap the library calls in functions which will return a status code, and if an exception occurred, a copy of the exception object.

最好的方法是什么存储异常(具有多态行为)供以后使用?我相信c ++ 0x将来的API会使用类似这样的东西。那么最好的方法是什么?

What is the best way to store an exception (with it's polymorphic behavior) for later use? I believe that the c++0x future API makes use of something like this. So what is the best approach?

我能想到的最好的方法是在其中使用 clone()方法每个异常类都将返回一个指向相同类型异常的指针。但这不是很通用,根本不处理标准异常。

The best I can think of is to have a clone() method in each exception class which will return a pointer to an exception of the same type. But that's not very generic and doesn't deal with standard exceptions at all.

有什么想法吗?

编辑:c ++ 0x似乎具有一种机制。它被描述为图书馆魔术。这是否意味着不需要c ++ 0x的任何语言功能?如果没有,是否有任何与c ++ 03兼容的实现?

EDIT: It seems that c++0x will have a mechanism for this. It is described as "library magic". Does that mean that is doesn't require any of the language features of c++0x? if not, are there any implementations which are compatible with c++03?

编辑:看起来boost具有实现异常复制。对于任何非<​​code> boost :: copy_exception 的答案,我都会保留该问题。

EDIT: Looks like boost has an implementation of exception copying. I'll keep the question open for any non boost::copy_exception answers.

编辑:解决j_random_hacker关于异常的根本原因是内存不足错误的担忧。对于这个特定的库和一组例外,情况并非如此。从根异常对象派生的所有异常代表由无效用户输入引起的不同类型的解析错误。与内存相关的异常只会导致引发 std :: bad_alloc 并单独处理。

EDIT: To address j_random_hacker's concerns about the root cause of the exception being an out of memory error. For this particular library and set of exceptions, this is not the case. All exceptions derived from the root exception object represent different types of parsing errors caused by invalid user input. Memory related exceptions will simply cause a std::bad_alloc to be thrown which is addressed separately.

推荐答案

您有我认为最好的答案,只有答案。您无法保留对原始异常的引用,因为它将离开范围。您只需复制它,唯一的通用方法就是使用诸如clone()之类的原型函数。

You have what would be what I think is your best, only answer. You can't keep a reference to the original exception because it's going to leave scope. You simply have to make a copy of it and the only generic way to do that is with a prototype function like clone().

对不起。

这篇关于在变量中存储异常的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆