繁体   English   中英

C++,标准库异常

[英]C++, Standard library Exceptions

在 C++ 中,“new.h”定义了下面的 class

class bad_alloc : public exception 
{
   public:
        bad_alloc() throw() { }
        virtual ~bad_alloc() throw();
};

构造函数和析构函数都明确指定不抛出异常,它没有其他成员函数,但它继承了“异常”class。

我的假设是“新”运算符使用此 class 在分配期间发生错误时引发异常。 但是怎么做? 没有有效的成员function,代码中实际是怎么使用的?

我想知道,这个 class "bad_alloc" 声明的用途是什么? 请帮我。

不需要成员函数 - 这是完全有效的:

throw 42;

大多数情况下,我们对异常的类型感兴趣,而不是其他。 然而,标准异常确实从异常基础 class 继承了一些函数。

异常并不真的需要有成员。 您声明这些类,以便您可以显式捕获它们:

try {
    Foo * foo = new Foo();
}
catch(std::bad_alloc &) {
    std::cout << "could not allocate" << std::endl;
}

类型的名称是所需的所有信息。 上面的语句将只捕获bad_alloc及其所有子类。

有效的成员函数继承自exception bad_alloc的目的是当您查找runtime_errorlogic_error时不会捕获它。

没有有效的成员function,代码中实际是怎么使用的?

此 class 的目的仅仅是向(向new的调用者)发出分配失败的信号(= 缺少可用内存)。 它不需要任何成员函数。

创建 class 的 object 然后抛出: throw bad_alloc(); . 本质上,您可以抛出任何 object 或值。 然后可以在catch()语句中使用它的类型来仅抓取这种异常。

例子:

try
{
   // some code throwing exceptions
}
catch(const bad_alloc&)
{
    // this code is only run if an object of class bad_alloc is thrown
}
catch(const exception&)
{
    // this code is run if an object of class exception (or any unhandled derivated class) is thrown
}

您也可以忽略此类类并仅抛出字符串(抛出“发生错误。”),但您无法区分它们,因此您要么处理所有字符串,要么不处理。

这是新操作员的代码。 没什么特别的。 它只是抛出这个 class 的一个实例。

#define _RAISE(x)   throw (x)

void *__CRTDECL operator new(size_t size) _THROW1(_STD bad_alloc)
        {       // try to allocate size bytes
        void *p;
        while ((p = malloc(size)) == 0)
                if (_callnewh(size) == 0)
                {       // report no memory
                static const std::bad_alloc nomem;
                _RAISE(nomem);
                }

        return (p);
        }

这是在某些例程未能分配 memory 的情况下引发的异常。 如果你想发出这样的信号,它就像这样使用:

throw std::bad_alloc();

此外,如果你想捕捉 memory 分配错误,它是这样的:

try {
    ...do something here...
} catch (const std::bad_alloc& ex) {
    ...print an error message or handle the exception in some other way...
}

new分配 memory 失败时会抛出bad_alloc异常。

经典的 C malloc()通过返回NULL指针来表示问题,但在 C++ 中, new运算符会引发异常。 然后,您可以捕获异常:

try {
    int * bigArray = new int[1024*1024*1024] ;
}
catch (bad_alloc& ex) { 
    cout<<"bad_alloc :"<<ex.what()<<endl ;
}

请注意,您可以使用特殊版本的new ,它不会引发异常,但会在出现错误时返回NULL指针。 您可以通过调用new (nothrow)而不是new来使用它

虽然要求 4 gigs 的 memory 很可能会导致可捕获的 std::bad_alloc 异常,但捕获 bad_alloc 通常有点冒险。

try {
  char * one_byte = new char(42);
}
catch (std::bad_alloc & except) {
  // Doing anything but calling exit here will almost certainly fail.
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM