473,811 Members | 2,540 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Cannot catch OutOfMemoryExce ption.

I have a problem with catching the OutOfMemoryExce ption in a managed C+
application. When creating small objects on the managed heap neithe
the catch handler for OutOfMemoryExce ption nor the UnhandledExcept io
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::Collect ions
using namespace System::Threadi ng
using namespace System::Diagnos tics

public __gc class Test

public

static void Main()

static void Test4::OnUnhand ledException( Object* pSender,
UnhandledExcept ionEventArgs* pArgs )

protected

static ArrayList* ms_pList = new ArrayList()
}

void Test4::Main(

AppDomain::Curr entDomain->UnhandledExcep tion += new UnhandledExcept ionEventHandler (
0, Test4::OnUnhand ledException )

tr

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

tr

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

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

catch(OutOfMemo ryException*

ms_pList->Clear()
Console::WriteL ine("OutOfMemor yException caught")

catch(...

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

catch(OutOfMemo ryException*

ms_pList->Clear()
Console::WriteL ine(S"OutOfMemo ryException caught in Main")

catch(...

Console::WriteL ine("Unexpected exception caught")
Console::WriteL ine(S"Applicati on finished normally")
Console::WriteL ine(S"Press <Enter> to exit")
Console::ReadLi ne()
void Test4::OnUnhand ledExceptio

Object* pSender,
UnhandledExcept ionEventArgs* pArg
ms_pList->Clear()
GC::Collect()
Console::WriteL ine(S"Unhandled exception caught:")
Console::WriteL ine(S"Press <Enter> to exit")
Console::ReadLi ne()
Process::GetCur rentProcess()->Kill()
Best regards
Michael
Nov 17 '05 #1
3 6011
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 ( nameOfYourFunct ion );

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_handle r. 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_handle r( _PNH ) that is implemented by the CRT as far as I know an
new_handler _set_new_handle r( 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
OutOfMemoryExce ption 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*******@disc ussions.microso ft.com> wrote in message
news:1F******** *************** ***********@mic rosoft.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_handle r. 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 r _PNH _set_new_handle r( _PNH ) that is implemented by the CRT as far as I know and new_handler _set_new_handle r( 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 OutOfMemoryExce ption 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
27393
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 that catches an expected exception. The method in the DLL throws the exception back out. When in debug mode, the process just exits.
9
343
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 Exceptions, or if I simply do the following: try
3
2896
by: Steve | last post by:
I have some general catch clauses in my app as follows: try { } catch(Exception ex) { } try
13
3727
by: Benny | last post by:
Hi, I have something like this: try { // some code } catch // note - i am catching everything now {
2
4449
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 then skip this file and move onto the next file (line). If file is there then move to a sirectory. Here is the code I have (Feel free to make corrections as needed. If possible make changes in red)
3
1849
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 something but my codes breaks at the difition of my class: "Public Class MainForm" ....so I'm assuming that the OutOfMemoryException occurs in the 3rd party since I have put a Try-Catch block around my bitmap creation code and I am
5
3406
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 operations are all within Try Catches to help me locate the problem and the origination of any problem by specifiying an error code in the "Catch" section. So theoretically this shouldn't have been possible (at which point we all say "yeah,...
23
2335
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
1676
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,...) marked as static as opposed to private? Also, is it not best to include the objConn.Open(); statement in the try block instead of just the objCmd.ExecuteNonQuery(); statement. Suppose the db server wa not found, etc., would that error still be...
0
9730
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9605
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10392
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10403
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9208
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7671
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6893
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
4341
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
3020
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.