简体   繁体   English

如何从C#处理非托管Win32异常

[英]How to handle unmanaged Win32 exception from C#

Hi guys I'm trying to figure out whether it is possible to catch(or at least suppress) all kinds of unmanaged exceptions in managed code? 嗨,大家好,我想弄清楚是否有可能在托管代码中捕获(或至少抑制)各种非托管异常? I've seen a lot of questions here already but it is still unclear for me, what types of exceptions are catchable and what are not? 我已经在这里看到了很多问题,但是对于我来说仍然不清楚,哪些类型的异常是可捕获的,哪些不是?

Just as an example i've made a C++ programm that performs division by zero: 举例来说,我制作了一个C ++程序,该程序执行零除:

printf("Hello from unmanaged code\n");
int a = 0;
printf("%d\n", 10 / a);
return 0;

And a C# application 还有一个C#应用程序

        try
        {
            Process p = new Process();
            p.StartInfo.FileName = "test.exe";
            p.Start();
            p.WaitForExit();
            Console.WriteLine("success");
        }
        catch (Win32Exception)
        {
            Console.WriteLine("1");
        }
        catch(ExternalException)
        {
            Console.WriteLine("2");
        }
        catch
        {
            Console.WriteLine("3");
        }

None of the catchs here does not trigger, program termintaion window appeares and after closing it, C# programm continues normal execution. 这里没有任何捕获不会触发,程序终止窗口出现,并且关闭它之后,C#程序将继续正常执行。

无论使用何种语言或使用catch块, 您都无法处理来自不同进程的异常

As mentioned by nvoigt you can not handle exception in this case. 如nvoigt所述,在这种情况下,您无法处理异常。 a more suitable solution for this case is reading the returned value from C++ code. 对于这种情况,更合适的解决方案是从C ++代码读取返回的值。 for example : if (a != 0) return 1; 例如:if(a!= 0)返回1; then handling it in your C# code like: if (p.ExitCode == 1) Console.WriteLine("division by zero"); 然后在您的C#代码中进行处理,例如:if(p.ExitCode == 1)Console.WriteLine(“除以零”);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM