为什么win32异常不被c#异常处理机制所捕获 [英] Why win32 exception are not caught by c# exception handling mechanism

查看:123
本文介绍了为什么win32异常不被c#异常处理机制所捕获的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个winforms应用程序.Winforms从Program.cs开始,我们有main()定义。我把这段代码放在try-catch块中。

I have a winforms application.Winforms start with Program.cs where we have main() defined.I have put this code in try-catch block.

 [STAThread]
    static void Main()
    {
        try
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new frmSplash());
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
            if (ex.InnerException != null)
            {
                MessageBox.Show(ex.InnerException.ToString());
            }
        }
    }

每当有一个win32异常,此机制失败,并且未处理的异常消息被抛出并且应用程序崩溃。

我有两个有关此代码的问题:

Whenever there is a win32 exception,this mechanism fails and unhandled exception message is thrown and application crashes.
I have 2 questions regarding this code:

1)为什么win32异常没有被抓住。

1) Why win32 exceptions are not caught.

2)在最高级别捕获异常是一个很好的做法。

2) Is it a good practice to catch exceptions at the highest level.

推荐答案

编辑 Pratik 指出,以下答案适用到.NET 1.0和.NET 1.1。从.NET 2.0开始,非CLS异常应该被捕获为 RuntimeWrappedException

EDIT : as Pratik pointed out, the following answer applies to .NET 1.0 and .NET 1.1 only. Starting with .NET 2.0, non-CLS exception should be caught as a RuntimeWrappedException.

因为Win32异常不是从.NET派生的异常类。尝试:

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

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

请参阅在一般处理程序中捕获非CLSCompliant异常以获取更多信息。

See Catch non-CLSCompliant exceptions in general handlers for more information.

这篇关于为什么win32异常不被c#异常处理机制所捕获的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆