473,805 Members | 2,111 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Unmanaged exception caught how in managed code?

Suppose the following:

// Unmanaged code
class UnmanagedExcept ion /* not visible outside of unmanaged code */
{
};
void DoSomething() /* visible (exported) to managed code */
{
throw new UnmangedExcepti on();
}

// Managed code
// Call into unmanaged code
try
{
DoSomething();
}
catch (???)
{
}
What is/are suitable types to catch in the managed code?

I see SEHException and its parent ExternalExcepti on, but these (automatic)
wrappers seem to be based on COM hresult types of exceptions.

My understanding is that the managed framework automatically catches,
repackages, and rethrows the unmanaged exception, but as what?

Thanks

--
Bret Pehrson
mailto:br**@inf owest.com
NOSPAM - Include this key in all e-mail correspondence <<38952rglkwdsl >>
Nov 17 '05 #1
12 13793
Hello Bret,

Thanks for posting in the group.

Based on the description, the question is: How to trap a unmanged type
exception in managed code? Please feel free to post here if I misunderstood
the question.

In fact, we can catch the common language runtime exception
(System::Except ion) and the unmanaged exception (C++ struct) in Managed
Extensions for C++ code. Please refer to the following sample code:

#using <mscorlib.dll >
using namespace System;

struct S {
};

void foo(int i) {
if (i == 0) {
throw (new S());
}
else {
Exception *e = new Exception;
throw e;
}
}

int main() {
int nRes = 1;
for (int i = 0; i < 2; i++) {
try {
foo(i);
}
catch (S* s) {
(s);
Console::WriteL ine(S"Caught an unmanaged exception!");
nRes -= 2*i;
}
catch (Exception* e) {
Console::WriteL ine(S"Caught a managed exception: {0}", e->ToString());
nRes -= i;
}
}

return nRes;
}

Note that the same try block is guarded by both of the catch statements
that catch managed and unmanaged exceptions individually. Also note that
the code generated by this sample is completely managed code.

You can also refer to
http://msdn.microsoft.com/library/en...edsampledemons
tratesthrowingc atchingmanagedu nmanagedexcepti onswithinsingle process.asp?fra m
e=true for the details on this sample.

Does that answer your question?

Best regards,
Yanhong Huang
Microsoft Community Support

Get Secure! ¨C www.microsoft.com/security
This posting is provided "AS IS" with no warranties, and confers no rights.

Nov 17 '05 #2
Hi Bret,
You can catch unmanaged exception in c# but you can't use them. you can only
rethrow them

if you have try/catch block like this
try
{
....
}
catch
{
...
throw;
}

the catch block will catch all exceptions (managed and unmanaged) and the
*thow* operator will rethrow catched exception *AS IS*.

This is the only way you can catch unmanaged exception with try/catch block
in c# and your choices are either to swallow it or rethrow it.

--
B\rgds
100
"Bret Pehrson" <br**@infowest. com> wrote in message
news:40******** *******@infowes t.com...
Suppose the following:

// Unmanaged code
class UnmanagedExcept ion /* not visible outside of unmanaged code */
{
};
void DoSomething() /* visible (exported) to managed code */
{
throw new UnmangedExcepti on();
}

// Managed code
// Call into unmanaged code
try
{
DoSomething();
}
catch (???)
{
}
What is/are suitable types to catch in the managed code?

I see SEHException and its parent ExternalExcepti on, but these (automatic)
wrappers seem to be based on COM hresult types of exceptions.

My understanding is that the managed framework automatically catches,
repackages, and rethrows the unmanaged exception, but as what?

Thanks

--
Bret Pehrson
mailto:br**@inf owest.com
NOSPAM - Include this key in all e-mail correspondence <<38952rglkwdsl >>

Nov 17 '05 #3
I know this is really a nit-picky question, but I'm still getting
to grips with MC++'s rules and regs:

//> throw (new S());
throw S(); // Do we need to allocate from the freestore?

//> catch (S* s) {
catch (S& s) // Isn't it preferable to catch by reference?

//> (s); // What does this do?

You mention that all the resulting code is managed. Is the 'new S()'
required to make this the case?

Thanks.
Arnold the Aardvark
http://www.codeproject.com/cpp/garbage_collect.asp

Nov 17 '05 #4
Hello,

For your quesitons,

1) and 2):
throw S() --> catch (S& s)
throw ( new S()) --> catch ( S* s)
3) If you add a constructor to struct S, you can see that (s) will call its
constructor.
For an example,
struct S {
S(){Console::Wr iteLine ("enter structure S");}
};

4) new S() is not related to managed or unmanged.

Thanks.

Best regards,
Yanhong Huang
Microsoft Community Support

Get Secure! ¨C www.microsoft.com/security
This posting is provided "AS IS" with no warranties, and confers no rights.

Nov 17 '05 #5
> 3) If you add a constructor to struct S, you can see that (s) will call
its constructor.
But the object is already fully constructed in the throw statement.
Am I being obtuse? I've never C++ like this before.
4) new S() is not related to managed or unmanged.


Thanks. That's what I wanted to know.
Arnold the Aardvark
http://www.codeproject.com/cpp/garbage_collect.asp

Nov 17 '05 #6
Yan-Hong Huang[MSFT] <yh*****@online .microsoft.com> wrote:
[...]
4) new S() is not related to managed or unmanged.
I wouldn't know about MC++, but in
std C++ 'throw new S()' certainly
seems a very bad idea.
Thanks.

Best regards,
Yanhong Huang

Schobi

--
Sp******@gmx.de is never read
I'm Schobi at suespammers dot org

"Sometimes compilers are so much more reasonable than people."
Scott Meyers
Nov 17 '05 #7
Hi Schobi,

You are correct. This is just extracted from some sample code. throw S()
--> catch (S& s) is better.

While the Standard doesn't specify where the exception object in catch (xc
& x) is stored, most implementation maintain a special exception stack, on
which exception are constructed (however, the Standard does not allow the
implementation to use free store memory for that purpose). Passing an
exception by reference is preferred to passing an exception by value for
several reasons: as you suggested, it short circuits the process of passing
the exception object to its handler (only a reference is copied rather than
a full-blown object). However, pass by reference also ensures that derived
exceptions are not sliced. Finally, it enables you to modify the exception
and then pass it on to another handler (i.e., a re-throw) with the changes
made to that object.

Thanks for pointing it out. :)

Best regards,
Yanhong Huang
Microsoft Community Support

Get Secure! ¨C www.microsoft.com/security
This posting is provided "AS IS" with no warranties, and confers no rights.

Nov 17 '05 #8
Hi Arnold,

Sorry for my mistake. (s) has no effects here. By using ildasm.exe, you can
see that this sentence is ignored by compiler and have no effect.

It just likes:
struct S a;
(a);

It can pass building.

BTW, if you want the struct is managed code, you need to define it as: __gc
struct...

Thanks very much.

Best regards,
Yanhong Huang
Microsoft Community Support

Get Secure! ¨C www.microsoft.com/security
This posting is provided "AS IS" with no warranties, and confers no rights.

Nov 17 '05 #9
Mhmm. While catching by reference certainly
is better than catching by value (beeing
who I am I mostly catch by const reference),
actually I was refereing to your
throw new S()
as this begs the question of who will be
responsible for deleting the object.

Schobi
Yan-Hong Huang[MSFT] <yh*****@online .microsoft.com> wrote:
Hi Schobi,

You are correct. This is just extracted from some sample code. throw S()
--> catch (S& s) is better.

While the Standard doesn't specify where the exception object in catch (xc
& x) is stored, most implementation maintain a special exception stack, on
which exception are constructed (however, the Standard does not allow the
implementation to use free store memory for that purpose). Passing an
exception by reference is preferred to passing an exception by value for
several reasons: as you suggested, it short circuits the process of passing
the exception object to its handler (only a reference is copied rather than
a full-blown object). However, pass by reference also ensures that derived
exceptions are not sliced. Finally, it enables you to modify the exception
and then pass it on to another handler (i.e., a re-throw) with the changes
made to that object.

Thanks for pointing it out. :)

Best regards,
Yanhong Huang
Microsoft Community Support

Get Secure! ¨C www.microsoft.com/security
This posting is provided "AS IS" with no warranties, and confers no rights.


--
Sp******@gmx.de is never read
I'm Schobi at suespammers dot org

"Sometimes compilers are so much more reasonable than people."
Scott Meyers
Nov 17 '05 #10

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

Similar topics

0
1014
by: James L. Brown | last post by:
Hello I'm currently working on a project, that contains one .net (VB) executable and a C++ (MFC) DLL. Now, what I want to do is to call the functions in the dll out of my managed code //managed cod Public Class Win32Call <StructLayout(LayoutKind.Sequential)> Class MYSTRUC Public counter1 As Int6 Public counter2 As Int6 End Clas
2
2613
by: Bret Pehrson | last post by:
Suppose the following: // Unmanaged code class UnmanagedException /* not visible outside of unmanaged code */ { }; void DoSomething() /* visible (exported) to managed code */ { throw new UnmangedException(); }
2
2412
by: Brett Styles | last post by:
Hi Guys, I am trying to access a class in an unmanaged dll. I have created a wrapper managed class to access the functions I need but no matter what I try from the MSDN samples I can not get it to work with my code. I have a VB Net front end which need the access the unmanaged functions. The wrapper I wrote can be accessed but the wrapper will not compile when I refer to the unmanaged class. I have tried using header file for definitions...
12
6121
by: Vasco Lohrenscheit | last post by:
Hi, I have a Problem with unmanaged exception. In the debug build it works fine to catch unmanaged c++ exceptions from other dlls with //managed code: try { //the form loads unmanaged dlls out of which unmanaged exception //get thrown
1
2264
by: RaKKeR | last post by:
Hi, I'm trying to wrap my unmanaged c++ code into a managed c++ wrapper. The problem is VC .NET doesn't seem to find the namespaces defined in my unmanaged code. Let's say I have a file "server.h" with a namespace server. When I include this file in another file that will be compiled as managed, the compiler gives me the following error: C2871: 'server' : a namespace with this name does not exist
5
2404
by: Andy | last post by:
I'm having trouble accessing an unmanaged long from a managed class in VC++.NET When I do, the contents of the variable seem to be mangled. If I access the same variable byte-by-byte, I get the correct value. Regardless what I set the variable to, the value that is returned for a long is always the same value. What's going on...can anyone help me? A short version of the code follows:
2
7554
by: =?Utf-8?B?Y2pz?= | last post by:
Hi, I have CLI/C++ code to override WndProc(Message% m) in order to create NC area. I tried to marshal unmanaged ptr (m.LParam) to managed object by using Marshal::PtrToStructure like: if (m.WParam == IntPtr(1)) { NCCALCSIZE_PARAMS csp; csp = (NCCALCSIZE_PARAMS)Marshal::PtrToStructure(m.LParam,
8
1773
by: LeXave | last post by:
Hi all In C++/CLI, is there a way to free an array allocated from an unmanaged dll ? In my managed code, I call a function from that dll which returns me an array of bytes. But how can I free it ? Thanks
4
6175
by: sree83 | last post by:
Hi All, I am having an executable developed in C#.Net. My app make use of services from some unmanaged dlls it loads. My problem is that my application is termainted due to some exceptions within these unmanaged codes. I tried AppDomain UnhandledExceptionEventHandler and ThreadExceptionEventHandler....but it fails to catch the excpetions... Can anyone tell me how to handle the unmanaged exceptions in manged code in. Thanks in...
0
9718
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
9596
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
10614
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10369
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
10109
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6876
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();...
0
5678
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4327
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
2
3847
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.