首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >c++异常:抛出std::string

c++异常:抛出std::string
EN

Stack Overflow用户
提问于 2008-09-25 17:05:37
回答 3查看 171.5K关注 0票数 82

当我的C++方法遇到一些奇怪的东西并且不能恢复时,我想抛出一个异常。可以抛出一个std::string指针吗?

这是我期待做的事情:

代码语言:javascript
复制
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;
    }
}
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2008-09-25 17:16:46

是。std::exception是C++标准库中的基本异常类。您可能希望避免将字符串用作异常类,因为它们本身会在使用过程中引发异常。如果发生这种情况,你会在哪里?

boost在异常和错误处理的良好风格上有一个很好的document。这本书值得一读。

票数 102
EN

Stack Overflow用户

发布于 2008-09-25 17:14:32

所有这些工作:

代码语言:javascript
复制
#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。请注意,在最不可取的选项中,需要显式释放内存。

票数 25
EN

Stack Overflow用户

发布于 2008-09-25 17:09:33

它是有效的,但如果我是你,我不会这么做。完成后,您似乎没有删除该堆数据,这意味着您已经创建了一个内存泄漏。C++编译器负责确保异常数据在堆栈弹出时保持活动状态,因此不需要使用堆。

顺便说一句,抛出std::string不是最好的开始方法。如果使用简单的包装器对象,将来会有更大的灵活性。它现在可能只封装了一个string,但也许将来你会想要包含其他信息,比如一些导致异常的数据,或者可能是一个行号(非常常见)。您不希望在代码库中的每个位置都更改所有的异常处理,所以现在就走正道,不要抛出原始对象。

票数 8
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/134569

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档