Exception handling, vraagje.

Status
Niet open voor verdere reacties.

CanTBeaTme

Banned
Lid geworden
25 jul 2006
Berichten
235
ik ben wat aant prullen ivb met exception handling maar had een vraagje over dit raar fenomeen:

Code:
#include <iostream>
  using std::cin;
  using std::cout;
  using std::endl;
  using std::cerr;
#include <iomanip>
  using std::setbase;
#include <new>
using std::bad_alloc;



int main()
{
  double *ptr[1000];

  try
  {
  for (int x = 0; x<10000; x++)
  {

    ptr[x] = new double [5000000];
    cout << "allocated 5000000 doubles in " << x << endl;
  }
  }
  catch (bad_alloc & memoryAllocationException )
  {
    cerr <<"Exception occured: "<< memoryAllocationException.what() << endl;
  }
  return 0;
}

stukje van output:

allocated 5000000 doubles in 37
allocated 5000000 doubles in 38
allocated 5000000 doubles in 39
allocated 5000000 doubles in 40
allocated 5000000 doubles in 41

Exception occured: bad alloc exception thrown

allocated 5000000 doubles in 42
allocated 5000000 doubles in 43
allocated 5000000 doubles in 44
allocated 5000000 doubles in 45
allocated 5000000 doubles in 46
allocated 5000000 doubles in 47
allocated 5000000 doubles in 48
allocated 5000000 doubles in 49
allocated 5000000 doubles in 50

nou , je ziet het all, hij gooit een exception maar gaat daarna nog door met nieuwe ruimtes te maken?? hoe komt dit :/
 
ik weet niks af van exceptions in c/c++, maar ik dacht dat die expliciet moesten gethrowd worden om uit een lus te kunnen breken..

zou het niet kunnen dat de try binnen de lus moet staan? lijkt me logischer aangezien je niet 1 keer probeert om alles te alloceren, maar elke keer om een nieuw blok te alloceren.

Code:
for (int x = 0; x<10000; x++)
{
    try
    {
        ptr[x] = new double [5000000];
        cout << "allocated 5000000 doubles in " << x << endl;
    }
}
catch (bad_alloc & memoryAllocationException )
{
    cerr <<"Exception occured: "<< memoryAllocationException.what() << endl;
}
return 0;

--Johan
 
#include <iostream>
#include <iomanip>
#include <new>
#include <cstdlib>
#include <fstream>

using namespace std;


int main()
{
double *ptr[1000];

for (int x = 0; x<10000; x++)
{
try
{
ptr[x] = new double [5000000];
cout << "allocated 5000000 doubles in " << x << endl;
}
catch (bad_alloc & memoryAllocationException )
{
cerr <<"Exception occured: "<< memoryAllocationException.what() << endl;
break;

}

}

cin.get();
return 0;

}


dat is inderdaad gelukt zow :) maar ik moest de catch wel bij in de loop zetten,anders ging hij dus eerst die loop doen en daarna pas checken ( 10000 keer die loop dus! ) ben blij dat me geheugen niet gecrashed is, kon het nog optijd stoppen :D

in ieder geval bedantk
 
Status
Niet open voor verdere reacties.
Terug
Bovenaan Onderaan