Constructors, Destructors and Exception Handling - C++ Class

C++ examples for Class:Destructor

Description

Constructors, Destructors and Exception Handling

Demo Code

#include <iostream>
#include <new>  // bad_alloc class is defined here

int main(int argc, const char *argv[]) {
    double *ptr[50];

    try {// w ww.j  a  v  a  2 s .  c  om
        for (int i = 0; i < 50; ++i) {
            ptr[i] = new double[50000000];  // may throw exception
            std::cout << "ptr[" << i << "] points to 50,000,000 new doubles\n";
        }
    } catch (std::bad_alloc &memoryAllocationExeption) {
        std::cerr << "Exception occured: " << memoryAllocationExeption.what()
                  << std::endl;
    }
    return 0;
}

Result


Related Tutorials