C # 코드에서 네이티브 예외를 포착 할 수 있습니까?
C # 코드에서 일부 관리되지 않는 라이브러리의 깊은 곳에서 throw 된 네이티브 예외를 포착 할 수 있습니까? 그렇다면 그것을 잡기 위해 다르게 무엇을해야합니까? 아니면 표준 시도를합니까?
당신은 사용할 수 있습니다 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();
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);
}
}
}
()없이 Catch는 네이티브 예외를 포함하여 CLS 규격이 아닌 예외를 catch합니다.
try
{
}
catch
{
}
자세한 내용은 다음 FxCop 규칙을 참조하십시오. http://msdn.microsoft.com/en-gb/bb264489.aspx
C #과 네이티브 코드 사이의 interop 계층은 예외를 관리되는 양식으로 변환하여 C # 코드에서 포착 할 수 있도록합니다. .NET 2.0 catch (Exception)
부터는 복구 할 수없는 오류 이외의 오류를 포착해야합니다.
.NET Reflector를 사용하여 어딘가에 다음 코드를 보았습니다.
try {
...
} catch(Exception e) {
...
} catch {
...
}
음, C #은 System.Exception 클래스에서 파생되지 않은 예외를 throw하는 것을 허용하지 않습니다. 그리고 내가 아는 한 interop 마샬 러에 의한 예외 캐치는 System.Exception을 상속하는 예외 클래스에 의해 래핑됩니다.
그래서 제 질문은 System.Exception이 아닌 예외를 잡을 수 있는지 여부입니다.
이것은 당신이 말하는 네이티브 예외의 유형에 따라 다릅니다. SEH 예외를 언급하는 경우 CLR은 두 가지 중 하나를 수행합니다.
- 알려진 SEH 오류 코드의 경우 적절한 .Net 예외 (예 : OutOfMemoryException)에 매핑합니다.
- 매핑 할 수없는 (E_FAIL) 또는 알 수없는 코드의 경우 SEHException 인스턴스 만 발생 합니다.
이 두 가지 모두 간단한 "catch (Exception)"블록으로 포착됩니다.
The other type of native exception which can cross the native/managed boundary are C++ exceptions. I'm not sure how they are mapped/handled. My guess is that since Windows implements C++ exceptions on top of SEH, they are just mapped the same way.
Almost, but not quite. You will catch the exception with
try
{
...
}
catch (Exception e)
{
...
}
but you will still have potential problems. According to MSDN, in order to insure exception destructors are called you would have to catch like:
try
{
...
}
catch
{
...
}
This is the only way to insure an exception destructor is called (though I'm not sure why). But that leaves you with the tradeoff of brute force versus a possible memory leak.
Incidentally, if you use the (Exception e) approach you should know the different types of exceptions you might come across. RuntimeWrappedException is what any managed non-exception type will be mapped to (for languages that can throw a string), and others will be mapped, such as OutOfMemoryException and AccessViolationException. COM Interop HRESULTS or exceptions other than E___FAIL will map to COMException, and finally at the end you have SEHException for E_FAIL or any other unmapped exception.
So what should you do? Best choice is don't throw exceptions from your unamanaged code! Hah. Really though if you have a choice, put up barriers and failing that make the choice of which is worse, a chance of a memory leak during exception handling, or not knowing what type your exception is.
If you use a
try
{
}
catch(Exception ex)
{
}
it will catch ALL exceptions, depending on how you call the external libraries you might get a com related exception that encapsulates the error but it will catch the error.
A standard try catch should do the trick i believe.
I run into a similar problem with a System.data exception throwing a sqlClient exception which was uncaught, adding a try..catch into my code did the trick in the instance
참고URL : https://stackoverflow.com/questions/150544/can-you-catch-a-native-exception-in-c-sharp-code
'Program Tip' 카테고리의 다른 글
암시 적으로 언 래핑 된 옵션으로 Swift 3 잘못된 문자열 보간 (0) | 2020.10.30 |
---|---|
이 파이썬 문자열의 크기가 실패한 int 변환에서 변경되는 이유 (0) | 2020.10.30 |
backbone.js 뷰를 기존 요소에 첨부하는 것과 el을 DOM에 삽입하는 것 비교 (0) | 2020.10.30 |
2011/2012의 Java JDBC 연결 풀 라이브러리 선택? (0) | 2020.10.30 |
Rust의 옵션 유형의 오버 헤드는 무엇입니까? (0) | 2020.10.30 |