你可以在C#代码中捕获本机异常吗? [英] Can you catch a native exception in C# code?

查看:138
本文介绍了你可以在C#代码中捕获本机异常吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#代码中,你可以捕获一些非托管库中抛出的本机异常吗?如果是这样,你需要做任何不同的事情来抓住它或做一个标准的尝试...抓住它?

解决方案

你可以使用 Win32Exception ,并使用其NativeErrorCode属性来处理它适当。

  // http://support.microsoft.com/kb/186550 
const int ERROR_FILE_NOT_FOUND = 2;
const int ERROR_ACCESS_DENIED = 5;
const int ERROR_NO_APP_ASSOCIATED = 1155;

void OpenFile(string filePath)
{
Process process = new Process();

尝试
{
//为文件类型
注册的本地应用程序调用//这可能会抛出本机异常
process.StartInfo.FileName = filePath ;
process.StartInfo.Verb =打开;
process.StartInfo.CreateNoWindow = true;
process.Start();
}
catch(Win32Exception e)
{
if(e.NativeErrorCode == ERROR_FILE_NOT_FOUND ||
e.NativeErrorCode == ERROR_ACCESS_DENIED ||
e .NativeErrorCode == ERROR_NO_APP_ASSOCIATED)
{
MessageBox.Show(this,e.Message,Error,
MessageBoxButtons.OK,
MessageBoxIcon.Exclamation);
}
}
}


In C# code can you catch a native exception thrown from deep in some unmanaged library? If so do you need to do anything differently to catch it or does a standard try...catch get it?

解决方案

You can use Win32Exception and use its NativeErrorCode property to handle it appropriately.

// http://support.microsoft.com/kb/186550
const int ERROR_FILE_NOT_FOUND = 2;
const int ERROR_ACCESS_DENIED = 5;
const int ERROR_NO_APP_ASSOCIATED = 1155; 

void OpenFile(string filePath)
{
    Process process = new Process();

    try
    {
        // Calls native application registered for the file type
        // This may throw native exception
        process.StartInfo.FileName = filePath;
        process.StartInfo.Verb = "Open";
        process.StartInfo.CreateNoWindow = true;
        process.Start();
    }
    catch (Win32Exception e)
    {
        if (e.NativeErrorCode == ERROR_FILE_NOT_FOUND || 
            e.NativeErrorCode == ERROR_ACCESS_DENIED ||
            e.NativeErrorCode == ERROR_NO_APP_ASSOCIATED)
        {
            MessageBox.Show(this, e.Message, "Error", 
                    MessageBoxButtons.OK, 
                    MessageBoxIcon.Exclamation);
        }
    }
}

这篇关于你可以在C#代码中捕获本机异常吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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