참을 수 없는 예외 처리의 편리함 :: 2007/11/22 13:34


윈도우 프로그래밍 테크닉
참을 수 없는 예외 처리의 편리함
신영진, codewiz@gmail.com, http://www.jiniya.net

윈도우는 오래 전부터 구조적 예외 처리(SEH, Structured Exception Handling)란 기법을 지원하고 있다. SEH의 사용법에 관해서는 이미 많은 책과 문서에서 소개했기 때문에 대부분의 개발자들이 그 사용법에 대해서 잘 알고 있다. 하지만 예외 처리 코드가 가지는 장점에 대해서 정확하게 이해하지 못해서 의외로 많은 개발자들이 실전에서 SEH나 C++의 예외처리 기능을 활용하지 못하고 있다. 이 글에서는 실패하지 않는 함수를 작성할 때에 SEH 코드가 가지는 장점에 대해서 설명한다.

우리가 오류나 예외란 상황에 접근하는 방법은 크게 두 가지다. 사전 처리와 사후 처리가 그것이다. 사전 처리란 어떠한 작업을 하기 전에 모든 조건이 완벽한지 검사를 하는 것이고, 사후 처리란 일단 작업을 하고 그것이 성공했는지 실패했는지를 살펴보는 것이다. 코드 상에서 사전 처리는 조건 검사를 의미하고 사후 처리는 예외 처리를 의미한다. 간단한 코드를 통해서 두 가지 접근 방법이 가지는 차이를 살펴보도록 하자.

리스트 1 출력용 포인터를 사용하는 함수

<리스트 1>에 나타난 것과 같이 포인터를 인자로 받아서 값을 기록하는 간단한 함수를 생각해보자. 이 코드에서 발생할 수 있는 문제는 무엇일까? <리스트 1>의 코드가 당연해 보인다면 심각한 문제가 있다

리스트 2 ASSERT를 사용한 검사

조금 숙련된 개발자라면 금방 <리스트 2>와 같은 코드를 생각해 낼 것이다. ASSERT는 실행 시간에 버그를 탐지하는데 굉장히 효율적인 방법이다. ASSERT 경고에 관한 활용에 대해서는 참고자료에 있는 “버그 안녕”이란 책을 살펴보도록 하자.

some_func2는 안전해 보이지만 단지 개발단계에서 버그를 탐지할 수 있다는 가능성만을 포함하고 있다. 또한 Release 버전에서는 대부분 제거되도록 매크로를 작성해두기 때문에 배포 버전에서 발생하는 문제에 대해서는 점검을 하기가 쉽지 않다. 그래서 배포 버전에서도 절대 실패해서는 안 되는 함수에 대해서는 적합하지 않은 방법이다.

리스트 3 if문을 통한 검사

배포 버전의 안정성까지 생각한다면 <리스트 3>과 같은 코드를 생각해볼 수 있다. 단순히 NULL 체크를 해서 안전한 경우에만 값을 복사하는 것이다. “이제는 끝이겠지?”라고 생각하면 오산이다. 과연 some_ptr에 값을 기록하는 행동이 NULL인 경우를 제외하면 모두 안전할까라는 생각을 해보아야 한다. 현재 프로세스에 맵핑되지 않은 메모리 라던지, 읽기 전용 속성으로 맵핑된 메모리 일수도 있다. 그런 경우에도 여전히 함수는 실패한다.

리스트 4 IsBadWritePtr을 통한 검사

이쯤 되면 이제 윈도우 API를 동원할 때가 되었다. <리스트 4>의 코드는 IsBadWritePtr을 통해서 해당 메모리가 쓰기 가능한지를 체크하는 함수다. 해당 API의 구현은 뒤로하더라도 이 정도면 some_ptr에 대한 기록을 하는 행동은 안전하다고 할 수 있다. 이 간단한 작업에도 이렇게 생각할 것이 많은 것이다.

리스트 5 SEH를 사용한 코드

<리스트 4>와 동일한 코드를 SEH로 작성한 것이 <리스트 5>의 코드다. 간단한 코드이기 때문에 코드만으로는 예외처리의 장점을 알기가 쉽지 않다. 단지 명확한 한 가지 단점은 복잡한 조건을 미리 생각하지 않아도 된다는 점이다. __try, __except 블록으로 인해 너무 복잡해 보인다거나, 예외처리 때문에 늦어진다고 불평을 할 수 있다. 하지만 이는 예외 처리에 대한 메커니즘을 정확하게 이해하지 못해서 발생하는 오류다. 우선 __try, __except 블록에 대해서 살펴보자. 분명히 <리스트 4>에는 그러한 것이 없다. 하지만 진짜 없는 것은 아니다. IsBadWritePtr이란 함수 속에 그 블록이 숨겨져 있을 뿐이다. 그렇다면 성능은 어떨까? <리스트 4>의 코드는 오류가 있건 없건 항상 IsBadWritePtr을 호출한다. 반면에 <리스트 5>의 코드는 그런 사전 검사에 드는 비용이 없다. 예외가 발생했을 때만 예외처리 코드가 수행된다. 따라서 <리스트 5>의 코드가 더 효율적이다.

복잡한 사전 조건을 모두 검사할 필요가 없다. 조건 검사 코드가 매번 실행되지 않기 때문에 효율적이다. 정상 코드와 예외 처리 코드가 분리되기 때문에 코드의 가독성이 증가한다. 개발자가 상상도 못했던 진짜 예외가 발생한 경우에도 대처할 수 있다. 큰 것만 생각해도 예외 처리가 가지는 장점은 이렇게 많다. 따라서 복잡한 조건 검사보다는 명확한 예외처리를 사용하는 것이 좋겠다.

SEH와 CRT
생각보다 많은 컴파일러 기능들이 CRT와 연결되어 있다. C++ 예외뿐만 아니라 SEH 또한 CRT 없이는 컴파일을 할 수가 없다. 예외 처리가 포함된 코드를 포함해서 컴파일을 하려고 하면 __except_handler3을 링크할 수 없다는 에러가 난다. Visual Studio에 번들 된 CRT 소스에도 이 함수는 포함되어 있지 않다. 그래서 자칫하면 CRT 없이는 예외처리를 사용할 수 없다고 생각하기 쉽다. 하지만 이는 진실이 아니다. 참고 자료에 있는 Matt Pietrek의 글을 읽으면 알 수 있겠지만 SEH는 근본적으로는 CRT와 상관이 없는 운영체제 기능이다. 컴파일러에서 CRT를 요구하는 이유는 컴파일러가 생성하는 코드에서 사용하는 SEH 필터 함수가 CRT에 포함되어 있기 때문이다.

이 문제를 해결하는 방법으로는 크게 세 가지 정도가 있다. DDK에 포함된 exsup.lib, sehupd.lib을 이용하는 방법, 경량 CRT 라이브러리인 tinycrt를 사용하는 방법, SEH 코드를 직접 구현해서 사용하는 방법이 그것이다.


참고자료
“버그 안녕! (Writing Solid Code)”
나윤석 옮김, 높이깊이

“Programming Applications for Windows (4/E)”
Jeffrey Richter, Microsoft Press

SEH 사용법
http://serious-code.net/moin.cgi/SEH

A Crash Course on the Depths of Win32™ Structured Exception Handling
http://www.microsoft.com/msj/0197/exception/exception.aspx

스폰서
글타래

  • 2주간 인기 글
  • 2주간 인기글이 없습니다.
Trackback Address :: http://jiniya.net/tt/trackback/655
  • on the page

    Tracked from on the page | 2020/11/10 15:53 | DEL

    괴짜 프로그래머의 일상사~@@ - 참을 수 없는 예외 처리의 편리함

  • by reference

    Tracked from by reference | 2021/02/19 04:03 | DEL

    괴짜 프로그래머의 일상사~@@ - 참을 수 없는 예외 처리의 편리함

  • 토토

    Tracked from 토토 | 2021/10/27 04:02 | DEL

    괴짜 프로그래머의 일상사~@@ - 참을 수 없는 예외 처리의 편리함

  • 바둑이

    Tracked from 바둑이 | 2021/10/27 05:55 | DEL

    괴짜 프로그래머의 일상사~@@ - 참을 수 없는 예외 처리의 편리함

  • 먹튀검증

    Tracked from 먹튀검증 | 2021/11/24 18:23 | DEL

    괴짜 프로그래머의 일상사~@@ - 참을 수 없는 예외 처리의 편리함

  • Gravatar Image.
    Maro | 2007/11/23 10:45 | PERMALINK | EDIT/DEL | REPLY

    와.. 항상 좋은글로 저의 머리속을 채워주시는군요 :)
    많이 배워갑니다 ㅋ_ㅋ)

  • Gravatar Image.
    eslife | 2007/11/24 04:54 | PERMALINK | EDIT/DEL | REPLY

    좋은 내용 잘 보고 갑니다.
    예전에 저희 직원은 try~catch 를 너무 사랑한 나머지 오류가 아닌데도 throw() 를 남발 한 적이 있었습니다. (에러를 리턴해야 하는데, 대신 throw() 발생)
    요것때문에 catch 를 하지 않은 다른 개발자는 프로그램이 죽어 버렸고, catch 에 의한 overhead 도 무시할 수 없을 만큼 크더군요.
    따로 링크 걸어 주신 SEH 사용법 도 내용 정말 좋네요. 잘 봤습니다 :)

    • Gravatar Image.
      codewiz | 2007/11/25 21:45 | PERMALINK | EDIT/DEL

      좋은 의견 감사합니다. 과하면 좋지 않다는 데에는 저도 같은 생각입니다. 특히나 예외적인 상황이 아닌 것까지 try,catch로 처리하는 것은 큰 문제죠.

      어디까지가 예외인가? 라는 질문에 대한 답을 하기가 참 쉽지 않은 것 같아요. 이것도 일종의 이념적인 성격이 강해서 말이죠. ^^;;

  • Gravatar Image.
    cek npwp aktif | 2020/04/18 17:49 | PERMALINK | EDIT/DEL | REPLY

    I would like to say that this blog really convinced me to do it! Thanks, very good post.
    <a href=https://biobalancepemf.com/ >bemer mats</a>

  • Gravatar Image.
    Meditacion | 2020/04/18 17:51 | PERMALINK | EDIT/DEL | REPLY

    I would like to say that this blog really convinced me to do it! Thanks, very good post.
    <a href=https://biobalancepemf.com/ >bemer mats</a>

  • Gravatar Image.
    chicken bus | 2020/05/02 22:14 | PERMALINK | EDIT/DEL | REPLY

    This is such a great resource that you are providing and you give it away for free. I love seeing websites that understand the value of providing a quality resource for free. It is the old what goes around comes around routine.

  • Gravatar Image.
    Cheap herbal incense | 2020/06/30 20:13 | PERMALINK | EDIT/DEL | REPLY

    I would like to thank you for the efforts you have made in writing this article. I am hoping the same best work from you in the future as well. Thanks...

  • Gravatar Image.
    advertising | 2020/07/02 21:46 | PERMALINK | EDIT/DEL | REPLY

    I haven’t any word to appreciate this post.....Really i am impressed from this post....the person who create this post it was a great human..thanks for shared this with us.

  • Gravatar Image.
    Anunturi Publicitare | 2020/07/04 19:55 | PERMALINK | EDIT/DEL | REPLY

    Thanks for posting this info. I just want to let you know that I just check out your site and I find it very interesting and informative. I can't wait to read lots of your posts.

  • Gravatar Image.
    Immobilie verkaufen | 2020/07/09 04:47 | PERMALINK | EDIT/DEL | REPLY

    This is my first time i visit here. I found so many interesting stuff in your blog especially its discussion. From the tons of comments on your articles, I guess I am not the only one having all the enjoyment here! keep up the good work

  • Gravatar Image.
    paving a driveway | 2020/07/11 10:20 | PERMALINK | EDIT/DEL | REPLY

    An fascinating discussion is value comment. I think that it is best to write extra on this matter, it won’t be a taboo topic however generally people are not enough to talk on such topics. To the next. Cheers

  • Thank you again for all the knowledge you distribute,Good post. I was very interested in the article, it's quite inspiring I should admit. I like visiting you site since I always come across interesting articles like this one.Great Job, I greatly appreciate that.Do Keep sharing! Regards,

  • Gravatar Image.
    acim | 2020/07/22 22:23 | PERMALINK | EDIT/DEL | REPLY

    Superbly written article, if only all bloggers offered the same content as you, the internet would be a far better place..

  • Very interesting blog. Alot of blogs I see these days don't really provide anything that I'm interested in, but I'm most definately interested in this one. Just thought that I would post and let you know.

  • Gravatar Image.
    vliegenval bestellen | 2020/07/27 20:51 | PERMALINK | EDIT/DEL | REPLY

    i read a lot of stuff and i found that the way of writing to clearifing that exactly want to say was very good so i am impressed and ilike to come again in future..

  • This is such a great resource that you are providing and you give it away for free. I love seeing blog that understand the value of providing a quality resource for free.

  • Gravatar Image.
    bitcoin news | 2020/08/05 00:23 | PERMALINK | EDIT/DEL | REPLY

    You completed a few fine points there. I did a search on the subject and found nearly all persons will go along with with your blog.

  • Gravatar Image.
    find here | 2020/08/09 18:35 | PERMALINK | EDIT/DEL | REPLY

    Most of the time I don’t make comments on websites, but I'd like to say that this article really forced me to do so. Really nice post!

  • Gravatar Image.
    find more | 2020/08/12 00:27 | PERMALINK | EDIT/DEL | REPLY

    This is just the information I am finding everywhere. Thanks for your blog, I just subscribe your blog. This is a nice blog..

  • Gravatar Image.
    Workout | 2020/08/13 21:27 | PERMALINK | EDIT/DEL | REPLY

    I am happy to find this post Very useful for me, as it contains lot of information. I Always prefer to read The Quality and glad I found this thing in you post. Thanks

  • Gravatar Image.
    read here | 2020/08/18 01:51 | PERMALINK | EDIT/DEL | REPLY

    I can see that you are an expert at your field! I am launching a website soon, and your information will be very useful for me.. Thanks for all your help and wishing you all the success in your business.

  • Gravatar Image.
    rug cleaning | 2020/09/20 20:24 | PERMALINK | EDIT/DEL | REPLY

    Hello, I have browsed most of your posts. This post is probably where I got the most useful information for my research. Thanks for posting, maybe we can see more on this. Are you aware of any other websites on this subject.

  • Gravatar Image.
    immigration attorney | 2020/09/28 01:49 | PERMALINK | EDIT/DEL | REPLY

    I’ve been searching for some decent stuff on the subject and haven't had any luck up until this point, You just got a new biggest fan!..

  • Gravatar Image.
    land clearing | 2020/10/03 18:00 | PERMALINK | EDIT/DEL | REPLY

    Interesting post. I Have Been wondering about this issue, so thanks for posting. Pretty cool post.It 's really very nice and Useful post.Thanks

  • Gravatar Image.
    tra giam can vytea | 2020/10/04 21:29 | PERMALINK | EDIT/DEL | REPLY

    I know your expertise on this. I must say we should have an online discussion on this. Writing only comments will close the discussion straight away! And will restrict the benefits from this information.

  • Great write-up, I am a big believer in commenting on blogs to inform the blog writers know that they’ve added something worthwhile to the world wide web!..

  • Great write-up, I am a big believer in commenting on blogs to inform the blog writers know that they’ve added something worthwhile to the world wide web!..

  • Gravatar Image.
    Christmas Cards | 2020/10/10 04:49 | PERMALINK | EDIT/DEL | REPLY

    I really enjoyed reading this post, big fan. Keep up the good work and please tell me when can you publish more articles or where can I read more on the subject?

  • Gravatar Image.
    product videos | 2020/10/18 17:30 | PERMALINK | EDIT/DEL | REPLY

    I can see that you are an expert at your field! I am launching a website soon, and your information will be very useful for me.. Thanks for all your help and wishing you all the success in your business.

  • Great write-up, I am a big believer in commenting on blogs to inform the blog writers know that they’ve added something worthwhile to the world wide web!..

  • I can see that you are an expert at your field! I am launching a website soon, and your information will be very useful for me.. Thanks for all your help and wishing you all the success in your business.

  • Gravatar Image.
    leaky gut diet | 2020/10/22 00:20 | PERMALINK | EDIT/DEL | REPLY

    Great write-up, I am a big believer in commenting on blogs to inform the blog writers know that they’ve added something worthwhile to the world wide web!..

  • Gravatar Image.
    locuri de munca | 2020/10/27 01:26 | PERMALINK | EDIT/DEL | REPLY

    This is just the information I am finding everywhere. Thanks for your blog, I just subscribe your blog. This is a nice blog..

  • Gravatar Image.
    spy game | 2020/11/22 18:26 | PERMALINK | EDIT/DEL | REPLY

    I really loved reading your blog. It was very well authored and easy to understand. Unlike other blogs I have read which are really not that good.Thanks alot!

  • Gravatar Image.
    domain for sale | 2020/11/22 22:29 | PERMALINK | EDIT/DEL | REPLY

    Fantastic blog! Do you have any tips and hints for aspiring writers? I’m planning to start my own website soon but I’m a little lost on everything. Would you propose starting with a free platform like WordPress or go for a paid option? There are so many options out there that I’m completely overwhelmed .. Any suggestions? Many thanks!

  • Gravatar Image.
    tiler Leeds | 2020/11/28 21:55 | PERMALINK | EDIT/DEL | REPLY

    Great articles and great layout. Your blog post deserves all of the positive feedback it’s been getting.

  • Interesting post. I Have Been wondering about this issue, so thanks for posting. Pretty cool post.It 's really very nice and Useful post.Thanks

  • Gravatar Image.
    derby printers | 2020/12/04 02:02 | PERMALINK | EDIT/DEL | REPLY

    I really loved reading your blog. It was very well authored and easy to understand. Unlike other blogs I have read which are really not that good.Thanks alot!

  • hello!! Very interesting discussion glad that I came across such informative post. Keep up the good work friend. Glad to be part of your net community.

  • Gravatar Image.
    maison intelligente | 2020/12/22 01:25 | PERMALINK | EDIT/DEL | REPLY

    Great write-up, I am a big believer in commenting on blogs to inform the blog writers know that they’ve added something worthwhile to the world wide web!..

  • Awesome blog. I enjoyed reading your articles. This is truly a great read for me. I have bookmarked it and I am looking forward to reading new articles. Keep up the good work

Name
Password
Homepage
Secret
< PREV | 1| ... 86|87|88|89|90|91|92|93|94| ... 604| NEXT >