C++ Tutorial/Exceptions/bad alloc Exception

Материал из C\C++ эксперт
Перейти к: навигация, поиск

Demonstrating standard new throwing bad_alloc when memory cannot be allocated

<source lang="cpp">#include <iostream> using std::cerr; using std::cout; using std::endl;

  1. include <new>

using std::bad_alloc; int main() {

  double *ptr[ 50 ];
  
  try 
  {
     for ( int i = 0; i < 50; i++ ) 
     {
        ptr[ i ] = new double[ 50000000 ];
        cout << "Allocated 50000000 doubles in ptr[ " << i << " ]\n";
     }
  }catch ( bad_alloc &memoryAllocationException )
  {
     cerr << "Exception occurred: " << memoryAllocationException.what() << endl;
  }
  
  return 0;

}</source>

Allocated 50000000 doubles in ptr[ 0 ]
Allocated 50000000 doubles in ptr[ 1 ]
Allocated 50000000 doubles in ptr[ 2 ]
Allocated 50000000 doubles in ptr[ 3 ]
Allocated 50000000 doubles in ptr[ 4 ]
Exception occurred: St9bad_alloc