473,396 Members | 2,002 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

Cannot catch OutOfMemoryException.

I have a problem with catching the OutOfMemoryException in a managed C+
application. When creating small objects on the managed heap neithe
the catch handler for OutOfMemoryException nor the UnhandledExceptio
handler is called in an out of memory situation. Instead the applicatio
writes 'Fatal out of memory' to the console and exits
Is this a bug in the runtime or am I missing something
Here is the example code

#include "stdafx.h
#using <mscorlib.dll

using namespace System
using namespace System::Collections
using namespace System::Threading
using namespace System::Diagnostics

public __gc class Test

public

static void Main()

static void Test4::OnUnhandledException( Object* pSender,
UnhandledExceptionEventArgs* pArgs )

protected

static ArrayList* ms_pList = new ArrayList()
}

void Test4::Main(

AppDomain::CurrentDomain->UnhandledException += new UnhandledExceptionEventHandler(
0, Test4::OnUnhandledException )

tr

for( int n = 0 ; n < 10; ++n

tr

Console::WriteLine("Allocating objects ...")
int i = 0
for( int m = 0; m < 100000000; ++m

ms_pList->Add(__box(i++))
Console::WriteLine("Clearing object list ...")
ms_pList->Clear()
Console::WriteLine("Garbage collection ...")
GC::Collect()

catch(OutOfMemoryException*

ms_pList->Clear()
Console::WriteLine("OutOfMemoryException caught")

catch(...

ms_pList->Clear()
Console::WriteLine("Unexpected exception caught")

catch(OutOfMemoryException*

ms_pList->Clear()
Console::WriteLine(S"OutOfMemoryException caught in Main")

catch(...

Console::WriteLine("Unexpected exception caught")
Console::WriteLine(S"Application finished normally")
Console::WriteLine(S"Press <Enter> to exit")
Console::ReadLine()
void Test4::OnUnhandledExceptio

Object* pSender,
UnhandledExceptionEventArgs* pArg
ms_pList->Clear()
GC::Collect()
Console::WriteLine(S"Unhandled exception caught:")
Console::WriteLine(S"Press <Enter> to exit")
Console::ReadLine()
Process::GetCurrentProcess()->Kill()
Best regards
Michael
Nov 17 '05 #1
3 5956
deb
Hi Michael

This is what I've used for insufficient memory. It's kind of dated, but it works! The set_new_handler( ) function was created to solve the universal problem of insufficient memory. It is defined in the new.h library. You use set_new_handler( ) by creating a function to handle the error, then passing that error-handling function's name (which is a pointer to the function) to the set_new_handler( ) function. The function you create to handle the error cannot return any values; it must be type void. Once you have created your error-handling function and your main( ) program, you must call set_new_handler( ) within your program with a statement that takes the following form:

set_new_handler( nameOfYourFunction );

Here's a quick example of mine

In main() or some other method, I have the statement

set_new_handler(noMem)

and for the method definition

void noMem(

cout << "no more memory " << endl
exit(1)
Nov 17 '05 #2
Hello deb

many thanks for your reply. I was so so impressed by all that pretty new .NET stuff tha
I really forgot about the good old _set_new_handler. But even that does not help
I tried it and got the same "Fatal out of memory". I tried both forms of _set_new_handle
_PNH _set_new_handler( _PNH ) that is implemented by the CRT as far as I know an
new_handler _set_new_handler( new_handler) that is implemented by the C++ std
Neither of them worked. As an additional test I tried allocating integers into a
std::vector<int>. In this case the new handler was called.
My interpretation of this behaviour is that the __gc heap bypasses the crt and allocate
memory by calling Windows API functions e.g. HeapCreate directly. When allocating smal
objects on the __gc heap the heap fills up so that there is no space left for creating an
OutOfMemoryException object. In this case the clr shuts down without giving you
application any chance to clean up. In my opinion this is a critical behaviour of the cl
that makes it nearly impossible to develop reliable applications using managed code

Best regards
Michael
Nov 17 '05 #3
I believe there are some CLR exceptions which cannot be caught in some or
all cases: OutOfMemory, StackOverflow, and ExecutionEngine.

I seem to remember reading that future versions of the CLR might allow you
to trap more cases of these errors, but I can't find where I read it
originally. In theory the CLR should be able to recover and let you release
references etc, but in practise it's very difficult (eg collecting an object
might involve JITing the finalizer... and the memory for that has to come
from somewhere).

Sorry I can't find the original article.
"Michael" <an*******@discussions.microsoft.com> wrote in message
news:1F**********************************@microsof t.com...
Hello deb,

many thanks for your reply. I was so so impressed by all that pretty new ..NET stuff that I really forgot about the good old _set_new_handler. But even that does not help. I tried it and got the same "Fatal out of memory". I tried both forms of _set_new_handler _PNH _set_new_handler( _PNH ) that is implemented by the CRT as far as I know and new_handler _set_new_handler( new_handler) that is implemented by the C++ std. Neither of them worked. As an additional test I tried allocating integers into an std::vector<int>. In this case the new handler was called.
My interpretation of this behaviour is that the __gc heap bypasses the crt and allocates memory by calling Windows API functions e.g. HeapCreate directly. When allocating small objects on the __gc heap the heap fills up so that there is no space left for creating an OutOfMemoryException object. In this case the clr shuts down without giving your application any chance to clean up. In my opinion this is a critical behaviour of the clr that makes it nearly impossible to develop reliable applications using managed code.
Best regards,
Michael

Nov 17 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
by: David | last post by:
I am having a bit of a problem with catching an exception within a thread. Here is the scenario: I have a Windows Form. I create a new thread. This new thread calls a method in another DLL...
9
by: Steven Blair | last post by:
Hi, I need to catch exceotions on File.Delete() After checking the help, I have noticed that thgere are serevral Exceptions that can be thrown. My question is, should I catch all thes...
3
by: Steve | last post by:
I have some general catch clauses in my app as follows: try { } catch(Exception ex) { } try
13
by: Benny | last post by:
Hi, I have something like this: try { // some code } catch // note - i am catching everything now {
2
by: Keith Kowalski | last post by:
I anm opening up a text file reading the lines of the file that refer to a tif image in that file, If the tif image does not exist I need it to send an email stating that the file doesn't exist...
3
by: elziko | last post by:
I have a procedure that creates a bitmap of a certain size and then displays it in a 3rd party component. However, if the bitmap is very large then a System.OutOfMemoryException is thrown my...
5
by: Simon Tamman {Uchiha Jax} | last post by:
Now this is bugging me. I just released software for a client and they have reported an unhandled stack overflow exception. My first concern is that the entirity of the UI and any threaded...
23
by: pigeonrandle | last post by:
Hi, Does this bit of code represent complete overkill?! try { //create a treenode TreeNode tn = new TreeNode(); //add it to a treeview tv.Nodes.Add(tn);
6
by: Jake K | last post by:
I've been reading throught MS article http://support.microsoft.com/kb/306636. I am in the process of learning C# and have a few questions. First, why are the methods (Pause, AddRecord,...)...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.