Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Try/Catch Block Fails to Catch Exception

Tags:

c#

exception

My program is generating a System.ComponentModel.Win32Exception within a try/catch block and the exception is not being caught. The code is very simple:

try
{
    lAFE.MinimumSize = sz1;  // lAFE=Label, sz1 = Size
}
catch (Exception ex)
{
    MessageBox.Show("afe: " + ex.Message);
}

The program runs through this code block hundreds of times without a problem then suddenly it generates this exception and it is not caught.

What can cause an exception like this not to be caught.

This application uses a lot of memory and the exception always occurs when the memory usage reaches about 305KB.

Any advice would be greatly appreciated.

like image 637
DPB Avatar asked Sep 15 '25 16:09

DPB


1 Answers

Because Win32 exceptions do not derive from the .NET Exception class. Try :

try 
{
} 
catch (Exception ex) 
{
    // .NET exception
} 
catch 
{
    // native exception
}

You can read this article:

A catch block that handles Exception catches all Common Language Specification (CLS) compliant exceptions. However, it does not catch non-CLS compliant exceptions. Non-CLS compliant exceptions can be thrown from native code or from managed code that was generated by the Microsoft intermediate language (MSIL) Assembler. Notice that the C# and Visual Basic compilers do not allow non-CLS compliant exceptions to be thrown and Visual Basic does not catch non-CLS compliant exceptions. If the intent of the catch block is to handle all exceptions, use the following general catch block syntax.

C#: catch {}

like image 71
mybirthname Avatar answered Sep 18 '25 05:09

mybirthname