Handling Native Exceptions in C# Code
In C#, it is possible to catch exceptions originating from unmanaged libraries. A standard try-catch block is sufficient to handle such exceptions. However, to access specific error information from the native exception, you can use the Win32Exception class.
The Win32Exception class provides a NativeErrorCode property that returns the native error code associated with the exception. You can use this property to perform specific handling or display custom error messages.
For instance, consider a scenario where you are attempting to open a file using a native application. The code below demonstrates how to handle potential exceptions, including native exceptions:
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 { 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); } } }
In this example, we catch the Win32Exception and check the NativeErrorCode property. If the error code matches one of the specified values (e.g., file not found, access denied, etc.), we display a custom error message.
The above is the detailed content of How Can I Handle Native Exceptions and Access Specific Error Information in C#?. For more information, please follow other related articles on the PHP Chinese website!