Microsoft MVP성태의 닷넷 이야기
.NET Framework: 104. Win32Exception 클래스 소개 [링크 복사], [링크+제목 복사],
조회: 23587
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 


Win32Exception 클래스 소개


.NET으로 Win32 API를 interop으로 호출을 할 때, 실패를 하면 그 원인을 알아낼 수 없어서 답답하지요. .NET에서는 Exception 클래스에서 친절한 오류 메시지를 알아낼 수 있지만, Win32 API를 호출했을 때는 그렇지 않습니다.

예를 들어 아래와 같은 OpenProcessToken이라는 Win32 API를 이용할 때,

[DllImport("advapi32.dll", SetLastError = true)]
public static extern bool OpenProcessToken(IntPtr processHandle, int acc, out IntPtr pHandleToken);

IntPtr tokenHandle = IntPtr.Zero;
IntPtr processHandle = new IntPtr(-2);

bool result
    = OpenProcessToken(processHandle,
    (int)(0x0020 | 0x00020000 | 0x0008),
    out tokenHandle);

위의 결과는 result == false가 나옵니다. 이런 경우, 왜 실패했는지를 알고 싶다면 Win32 API에서 제공되는 "GetLastError" API를 이용하면 되는데, 이 부분은 .NET BCL의 Marshal 타입에서 정적 메서드로 제공되고 있습니다. 그래서, 다음과 같이 그 원인을 알아낼 수 있습니다.

int errorCode = Marshal.GetLastWin32Error();

위와 같은 상황에서는 errorCode == 6입니다. 그런데, 6이라는 숫자가 어떤 걸 의미할까요? Visual C++에서는 Watch 윈도우의 변수에 ", hr"이라고 치면 오류값이 나옵니다. 아니면, 명령행 창에서 "NET HELPMSG <errorcode>"와 같이 치면 6에 대한 에러 메시지가 "The handle is invalid."라는 것을 알 수 있습니다. (Visual Studio 2008의 경우, C:\Program Files\Microsoft Visual Studio 9.0\Common7\Tools\errlook.exe를 이용하는 것도 가능합니다.)

그렇다면, 코드로는 어떻게 알아낼 수 있을까요?

Visual C++에서는 FormatMessage Win32 API를 이용해서 오류 메시지를 얻어낼 수 있는데요. 인터넷 검색을 해보시면 아시겠지만, 코드가 그다지 깔끔하게 나오지는 않습니다. 기왕이면, .NET에서 제공되는 좀 더 매끄러운 방법을 찾아보는 것이 좋겠지요. ^^

제가 처음에 생각해 냈던 것은 아래와 같은 코드였습니다.

int hr = Marshal.GetHRForLastWin32Error();
Exception ex = Marshal.GetExceptionForHR(hr);
string errorMessage = ex.Message;

실제로 errorMessage == "The handle is invalid. (Exception from HRESULT: 0x80070006 (E_HANDLE))"라고 해서 만족할 만한 수준입니다. 나름 위의 방법도 답이 될 수도 있지만, 원래 Microsoft에서 제공되는 전용 타입이 있는 데 그것이 바로 "Win32Exception"입니다.

그래서, 최종적으로 다음과 같이 코딩을 할 수 있습니다.

int errorCode = Marshal.GetLastWin32Error();
Exception ex = new Win32Exception(errorCode);
string errorMessage = ex.Message; // "The handle is invalid."





[이 토픽에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]







[최초 등록일: ]
[최종 수정일: 7/10/2021]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




1  2  3  4  5  [6]  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13857정성태1/7/20256893C/C++: 187. Golang - 콘솔 응용 프로그램을 Linux 데몬 서비스를 지원하도록 변경파일 다운로드1
13856정성태1/6/20255117디버깅 기술: 214. Windbg - syscall 단계까지의 Win32 API 호출 (예: Sleep)
13855정성태12/28/20247430오류 유형: 941. Golang - os.StartProcess() 사용 시 오류 정리
13854정성태12/27/20247215C/C++: 186. Golang - 콘솔 응용 프로그램을 NT 서비스를 지원하도록 변경파일 다운로드1
13853정성태12/26/20245684디버깅 기술: 213. Windbg - swapgs 명령어와 (Ring 0 커널 모드의) FS, GS Segment 레지스터
13852정성태12/25/20247294디버깅 기술: 212. Windbg - (Ring 3 사용자 모드의) FS, GS Segment 레지스터파일 다운로드1
13851정성태12/23/20245964디버깅 기술: 211. Windbg - 커널 모드 디버깅 상태에서 사용자 프로그램을 디버깅하는 방법
13850정성태12/23/20247622오류 유형: 940. "Application Information" 서비스를 중지한 경우, "This file does not have an app associated with it for performing this action."
13849정성태12/20/20247569디버깅 기술: 210. Windbg - 논리(가상) 주소를 Segmentation을 거쳐 선형 주소로 변경
13848정성태12/18/20246883디버깅 기술: 209. Windbg로 알아보는 Prototype PTE파일 다운로드2
13847정성태12/18/20246753오류 유형: 939. golang - 빌드 시 "unknown directive: toolchain" 오류 빌드 시 이런 오류가 발생한다면?
13846정성태12/17/20247594디버깅 기술: 208. Windbg로 알아보는 Trans/Soft PTE와 2가지 Page Fault 유형파일 다운로드1
13845정성태12/16/20245814디버깅 기술: 207. Windbg로 알아보는 PTE (_MMPTE)
13844정성태12/14/20248587디버깅 기술: 206. Windbg로 알아보는 PFN (_MMPFN)파일 다운로드1
13843정성태12/13/20246119오류 유형: 938. Docker container 내에서 빌드 시 error MSB3021: Unable to copy file "..." to "...". Access to the path '...' is denied.
13842정성태12/12/20246260디버깅 기술: 205. Windbg - KPCR, KPRCB
13841정성태12/11/20247176오류 유형: 937. error MSB4044: The "ValidateValidArchitecture" task was not given a value for the required parameter "RemoteTarget"
13840정성태12/11/20246170오류 유형: 936. msbuild - Your project file doesn't list 'win' as a "RuntimeIdentifier"
13839정성태12/11/20247555오류 유형: 936. msbuild - error CS1617: Invalid option '12.0' for /langversion. Use '/langversion:?' to list supported values.
13838정성태12/4/20247077오류 유형: 935. Windbg - Breakpoint 0's offset expression evaluation failed.
13837정성태12/3/20248022디버깅 기술: 204. Windbg - 윈도우 핸들 테이블 (3) - Windows 10 이상인 경우
13836정성태12/3/20245983디버깅 기술: 203. Windbg - x64 가상 주소를 물리 주소로 변환 (페이지 크기가 2MB인 경우)
13835정성태12/2/20247941오류 유형: 934. Azure - rm: cannot remove '...': Directory not empty
13834정성태11/29/20248007Windows: 275. C# - CUI 애플리케이션과 Console 윈도우 (Windows 10 미만의 Classic Console 모드인 경우) [1]파일 다운로드1
13833정성태11/29/20247290개발 환경 구성: 737. Azure Web App에서 Scale-out으로 늘어난 리눅스 인스턴스에 SSH 접속하는 방법
13832정성태11/27/20246853Windows: 274. Windows 7부터 도입한 conhost.exe
1  2  3  4  5  [6]  7  8  9  10  11  12  13  14  15  ...