当我的C++方法遇到一些奇怪的东西并且不能恢复时,我想抛出一个异常。可以抛出一个std::string
指针吗?
这是我期待做的事情:
void Foo::Bar() {
if(!QueryPerformanceTimer(&m_baz)) {
throw new std::string("it's the end of the world!");
}
}
void Foo::Caller() {
try {
this->Bar(); // should throw
}
catch(std::string *caught) { // not quite sure the syntax is OK here...
std::cout << "Got " << caught << std::endl;
}
}
发布于 2008-09-25 17:16:46
是。std::exception
是C++标准库中的基本异常类。您可能希望避免将字符串用作异常类,因为它们本身会在使用过程中引发异常。如果发生这种情况,你会在哪里?
boost在异常和错误处理的良好风格上有一个很好的document。这本书值得一读。
发布于 2008-09-25 17:14:32
所有这些工作:
#include <iostream>
using namespace std;
//Good, because manual memory management isn't needed and this uses
//less heap memory (or no heap memory) so this is safer if
//used in a low memory situation
void f() { throw string("foo"); }
//Valid, but avoid manual memory management if there's no reason to use it
void g() { throw new string("foo"); }
//Best. Just a pointer to a string literal, so no allocation is needed,
//saving on cleanup, and removing a chance for an allocation to fail.
void h() { throw "foo"; }
int main() {
try { f(); } catch (string s) { cout << s << endl; }
try { g(); } catch (string* s) { cout << *s << endl; delete s; }
try { h(); } catch (const char* s) { cout << s << endl; }
return 0;
}
您应该更喜欢h而不是f而不是g。请注意,在最不可取的选项中,需要显式释放内存。
发布于 2008-09-25 17:09:33
它是有效的,但如果我是你,我不会这么做。完成后,您似乎没有删除该堆数据,这意味着您已经创建了一个内存泄漏。C++编译器负责确保异常数据在堆栈弹出时保持活动状态,因此不需要使用堆。
顺便说一句,抛出std::string
不是最好的开始方法。如果使用简单的包装器对象,将来会有更大的灵活性。它现在可能只封装了一个string
,但也许将来你会想要包含其他信息,比如一些导致异常的数据,或者可能是一个行号(非常常见)。您不希望在代码库中的每个位置都更改所有的异常处理,所以现在就走正道,不要抛出原始对象。
https://stackoverflow.com/questions/134569
复制相似问题