处理特定的Win32异常(例如“未找到应用程序")的最佳方法是什么? [英] What is the best way to handle a specific Win32 Exception like "application not found"?

查看:192
本文介绍了处理特定的Win32异常(例如“未找到应用程序")的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用文件类型的默认应用程序启动了一个进程,但是如果用户删除了其默认应用程序,则会引发Win32Exception.此外,在其他情况下会引发Win32Exception,例如如果用户无权打开默认应用程序.

I start a process with the default application for the file type, but if the user has deleted his default application, a Win32Exception is thrown. In addition there are other cases when a Win32Exception is thrown e.g. if the user has no rights to open the default application.

现在,我正在寻找区分异常的最佳方法.

Now I'm looking for the best way to seperate between the exceptions.

我如何检查到底抛出了哪个异常?是通过异常消息检查它的唯一方法吗?

How can i check which exception exactly is thrown? Is the only way to check it by its Exception message?

我正在这样捕捉它:

        try
        {
            process.Start();
        }
        catch (Win32Exception exc)
        {
//How to check which exception exactly is thrown?
            return return string.Format("Process cannot be started", exc.Message)
        }

这是我首先想到的,但是我认为有一种更好的方法可以完成此任务:

This was mit first idea but i think there is a better way to accomplish this task:

catch (Win32Exception exc)
        {
            if(exc.Message == "Application not found")
            { 
              //Do something
            }
            else if(exc.Message == "Another exception")
            { 
              //Do something else
            }
        }

推荐答案

使用Win32Exception,您可能需要检查两者Win32Exception.NativeErrorCode及其继承的ExternalException.ErrorCode值.

With Win32Exception you may need to check both Win32Exception.NativeErrorCode and its inherited ExternalException.ErrorCode values.

C#6引入了异常过滤器,如果您打算重新引发异常,则允许您选择处理异常,而无需提前回退堆栈.

C# 6 introduces exception filters which allow you to opt-in to handling an exception without needing to rewind the stack prematurely if you intend to re-throw the exception.

Windows中的错误代码主要有三种类型:HRESULT,Win32错误代码和COM错误代码.

There are three main types of error-codes in Windows: HRESULT, Win32 Error Codes, and COM error codes.

  • HRESULT:

  • HRESULT值实际上是自我描述的位域,其格式记录在这里:
  • HRESULT values are actually self-describing bit-fields and the format is documented here: https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-erref/0642cb2f-2075-4469-918c-4441e69c548a
  • They're exposed as Exception.HResult.
  • Note that Exception.HResult has a default value of -2146233088 (0x80131500)

Win32错误代码:

Win32 error codes:

  • These are listed on this page: https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-erref/18d8fbe8-a967-4f1c-ae50-99ca8e491d2d?redirectedfrom=MSDN
  • They're exposed only on Win32Exception in the Win32Exception.NativeErrorCode property.

COM错误代码在此页面上列出: https://docs.microsoft.com/zh-cn/windows/win32/com/com-error-codes-1

COM error codes are listed on this page: https://docs.microsoft.com/en-us/windows/win32/com/com-error-codes-1

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