Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 
(연관된 글이 1개 있습니다.)
(시리즈 글이 4개 있습니다.)
디버깅 기술: 20. 예외 처리를 방해하는 WPF Modal 대화창
; https://www.sysnet.pe.kr/2/0/619

디버깅 기술: 21. 올바른 이벤트 예외 정보 출력
; https://www.sysnet.pe.kr/2/0/620

.NET Framework: 148. WPF - 데이터 바인딩 시의 예외 처리 방법
; https://www.sysnet.pe.kr/2/0/746

.NET Framework: 656. Windows Forms의 오류(Exception) 처리 방법에 대한 차이점 설명
; https://www.sysnet.pe.kr/2/0/11198




Windows Forms의 오류(Exception) 처리 방법에 대한 차이점 설명

다음의 질문에 달린 덧글에,

프로그램 비정상 종료 메시지 창 없애는 방법
; https://www.sysnet.pe.kr/3/0/4830

0으로 나누기 했을때의 메시지 창과 비정상 종료했을 때의 메시지 창 유형이 다르다고 나옵니다.

사실 이것은 0으로 나누기에 대한 문제가 아니라 Windows Forms이 제공하는 환경 위에서 오류가 발생했냐/안 했냐의 문제입니다. 예를 한번 들어 볼까요? ^^

간단하게 Windows Forms 위에 버튼을 하나 두고, 그 버튼 Click 이벤트에 다음의 코드를 넣어 실행해 봅니다.

private void button1_Click(object sender, EventArgs e)
{
    int a = 5;
    int b = 0;

    int c = a / b;
}

(버튼을 누르면, 당연히) 다음과 같은 오류 대화창이 뜨고,

error_handler_1.png

이때 Visual Studio를 이용해 디버거를 붙여 콜 스택을 확인하면 그 이유를 조사할 수 있습니다.

System.Windows.Forms.dll!System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(System.IntPtr dwComponentID, int reason, int pvLoopData)  Unknown
System.Windows.Forms.dll!System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(int reason, System.Windows.Forms.ApplicationContext context)    Unknown
System.Windows.Forms.dll!System.Windows.Forms.Application.ThreadContext.RunMessageLoop(int reason, System.Windows.Forms.ApplicationContext context) Unknown
System.Windows.Forms.dll!System.Windows.Forms.Application.RunDialog(System.Windows.Forms.Form form) Unknown
System.Windows.Forms.dll!System.Windows.Forms.Form.ShowDialog(System.Windows.Forms.IWin32Window owner)  Unknown
System.Windows.Forms.dll!System.Windows.Forms.Form.ShowDialog() Unknown
System.Windows.Forms.dll!System.Windows.Forms.Application.ThreadContext.OnThreadException(System.Exception t)   Unknown
System.Windows.Forms.dll!System.Windows.Forms.Control.WndProcException(System.Exception e)  Unknown
System.Windows.Forms.dll!System.Windows.Forms.Control.ControlNativeWindow.OnThreadException(System.Exception e) Unknown
System.Windows.Forms.dll!System.Windows.Forms.NativeWindow.Callback(System.IntPtr hWnd, int msg, System.IntPtr wparam, System.IntPtr lparam)    Unknown

그럼, 대화창을 실제로 만드는 코드를 OnThreadException에서 찾아볼 수 있습니다.

internal void OnThreadException(Exception t)
{
    if (!this.GetState(4))
    {
        this.SetState(4, true);
        try
        {
            ...[생략]...
            else if (SystemInformation.UserInteractive)
            {
                ThreadExceptionDialog dialog = new ThreadExceptionDialog(t);
                DialogResult oK = DialogResult.OK;
                IntSecurity.ModifyFocus.Assert();
                try
                {
                    oK = dialog.ShowDialog();
                }
            ...[생략]...
            }
            return;
        Label_0084:
            ...[생략]...
        }
        finally
        {
            this.SetState(4, false);
        }
    }
}

그리고 OnThreadException은 Windows 응용 프로그램의 필수 요소인 메시지 루프의 Win32 Message 처리 시 예외가 발생한 경우 수행된다는 것을 System.Windows.Forms.NativeWindow.Callback에서 찾아 볼 수 있습니다.

private IntPtr Callback(IntPtr hWnd, int msg, IntPtr wparam, IntPtr lparam)
{
    Message m = Message.Create(hWnd, msg, wparam, lparam);
    try
    {}
        if (this.weakThisPtr.IsAlive && (this.weakThisPtr.Target != null))
        {
            this.WndProc(ref m);
        }
        else
        {
            this.DefWndProc(ref m);
        }
    }
    catch (Exception exception)
    {
        this.OnThreadException(exception);
    }
    finally
    {
        if (msg == 130)
        {
            this.ReleaseHandle(false);
        }
        if (msg == NativeMethods.WM_UIUNSUBCLASS)
        {
            this.ReleaseHandle(true);
        }
    }
    return m.Result;
}

따라서, Win32 Message 처리 도중 예외가 발생한다면 .NET Windows Forms에서 마련한 예외 창이 뜨게 됩니다.

그렇다면, 당연히 다른 곳에서 예외가 발생하면 Windows Forms도 처리를 할 수 없으므로 시스템에 넘어가게 됩니다. 그 결과로 나온 아래와 같은 형식의 창은 (디버거 설치 유무 등의 정보 등을 조사한 다음 적절한 사후 처리를 할 수 있도록) 운영체제가 담당하게 됩니다. 다음은 디버거가 설치된 시스템에서 운영체제가 띄우는 오류 보고 창입니다.

error_handler_2.png

이를 테스트하고 싶다면 Windows Forms에 또 다른 버튼을 만들고 그 이벤트 핸들러에 다음과 같은 식으로 별도의 스레드를 이용해 처리를 맡겨 보면 됩니다.

private void button2_Click(object sender, EventArgs e)
{
    ThreadPool.QueueUserWorkItem((arg) =>
    {
        int a = 5;
        int b = 0;

        int c = a / b;
    }, null);
}

저 스레드에서는 Windows Forms의 Message Loop 처리 코드가 없기 때문에 예외가 발생하면 운영체제로 곧장 넘어가 비정상 종료를 하게 됩니다.




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 5/10/2017]

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)
13601정성태4/19/2024214닷넷: 2243. C# - PCM 사운드 재생(NAudio)파일 다운로드1
13600정성태4/18/2024283닷넷: 2242. C# - 관리 스레드와 비관리 스레드
13599정성태4/17/2024318닷넷: 2241. C# - WAV 파일의 PCM 사운드 재생(Windows Multimedia)파일 다운로드1
13598정성태4/16/2024347닷넷: 2240. C# - WAV 파일 포맷 + LIST 헤더파일 다운로드1
13597정성태4/15/2024419닷넷: 2239. C# - WAV 파일의 PCM 데이터 생성 및 출력파일 다운로드1
13596정성태4/14/2024789닷넷: 2238. C# - WAV 기본 파일 포맷파일 다운로드1
13595정성태4/13/2024912닷넷: 2237. C# - Audio 장치 열기 (Windows Multimedia, NAudio)파일 다운로드1
13594정성태4/12/20241018닷넷: 2236. C# - Audio 장치 열람 (Windows Multimedia, NAudio)파일 다운로드1
13593정성태4/8/20241050닷넷: 2235. MSBuild - AccelerateBuildsInVisualStudio 옵션
13592정성태4/2/20241207C/C++: 165. CLion으로 만든 Rust Win32 DLL을 C#과 연동
13591정성태4/2/20241169닷넷: 2234. C# - WPF 응용 프로그램에 Blazor App 통합파일 다운로드1
13590정성태3/31/20241073Linux: 70. Python - uwsgi 응용 프로그램이 k8s 환경에서 OOM 발생하는 문제
13589정성태3/29/20241143닷넷: 2233. C# - 프로세스 CPU 사용량을 나타내는 성능 카운터와 Win32 API파일 다운로드1
13588정성태3/28/20241197닷넷: 2232. C# - Unity + 닷넷 App(WinForms/WPF) 간의 Named Pipe 통신파일 다운로드1
13587정성태3/27/20241156오류 유형: 900. Windows Update 오류 - 8024402C, 80070643
13586정성태3/27/20241297Windows: 263. Windows - 복구 파티션(Recovery Partition) 용량을 늘리는 방법
13585정성태3/26/20241096Windows: 262. PerformanceCounter의 InstanceName에 pid를 추가한 "Process V2"
13584정성태3/26/20241049개발 환경 구성: 708. Unity3D - C# Windows Forms / WPF Application에 통합하는 방법파일 다운로드1
13583정성태3/25/20241158Windows: 261. CPU Utilization이 100% 넘는 경우를 성능 카운터로 확인하는 방법
13582정성태3/19/20241420Windows: 260. CPU 사용률을 나타내는 2가지 수치 - 사용량(Usage)과 활용률(Utilization)파일 다운로드1
13581정성태3/18/20241588개발 환경 구성: 707. 빌드한 Unity3D 프로그램을 C++ Windows Application에 통합하는 방법
13580정성태3/15/20241137닷넷: 2231. C# - ReceiveTimeout, SendTimeout이 적용되지 않는 Socket await 비동기 호출파일 다운로드1
13579정성태3/13/20241494오류 유형: 899. HTTP Error 500.32 - ANCM Failed to Load dll
13578정성태3/11/20241629닷넷: 2230. C# - 덮어쓰기 가능한 환형 큐 (Circular queue)파일 다운로드1
13577정성태3/9/20241876닷넷: 2229. C# - 닷넷을 위한 난독화 도구 소개 (예: ConfuserEx)
[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...