Demonstrate bad_alloc exception - C++ Statement

C++ examples for Statement:try catch

Description

Demonstrate bad_alloc exception

Demo Code

#include <iostream>
using namespace std;
int main()/*  ww w  .  j a  v  a2  s  .c o m*/
{
   const unsigned long SIZE = 10000;    //memory size
   char* ptr;                           //pointer to memory
   try
   {
      ptr = new char[SIZE];             //allocate SIZE bytes
   }
   catch(bad_alloc)                     //exception handler
   {
      cout << "\nbad_alloc exception: can't allocate memory.\n";
      return(1);
   }
   delete[] ptr;                        //deallocate memory
   cout << "\nMemory use is successful.\n";
   return 0;
}

Result


Related Tutorials