Skip to main content

Checked exception, 이거 써도 되나?

mkseo님 블로그Best Practices for Exception Handling에 관한 글이 올라왔는데 댓글을 읽고 쓰고 하다 궁금한게 생겼습니다.
Checked exception, 이거 써도 되나?
mkseo님이 링크를 걸어준 The Trouble with Checked ExceptionsDoes Java need Checked Exceptions?, Java's checked exceptions were a mistake (and here's what I would like to do about it)등의 글을 읽다 보니 현재까지의 결론은 "java의 checked exception실험은 실패다"정도인 것 같더군요.

몇가지 이유로는
  1. 원래 language designer의 의도와는 달리 많은 exception이 무시되고 있다. 원래 의도는 compile-time에 에러를 냄으로써 개발자들에게 이 예외를 지금 처리하거나 아니면 위로 전달해야 한다는 메시지를 보내는 것이었다. 하지만 예외를 전달하기 위해서는 method의 signature를 수정해야 한다. 개발자들로서는 이 상황을 벗어날 수 있는 가장 쉬운 방법을 찾게 되고, 이게 바로 catch 후 무시하는 것인데 대부분의 코드가 이런 식으로 작성되고 있다. catch (...) {}
  2. 원래 exception의 목적중 하나는 예외가 발생한 지점과 처리할 지점의 분리이다. 즉 low-level에서 발생했지만 거기서 처리가 불가능한 exception들을 위로 전달하여 처리하게 한다... 인데... checked exception은 그 사이에 있는 모든 코드가 이 exception에 대해 알아야만 하게 강제한다. 즉, 전달되는 과정이 투명하지 않다.
  3. Versionability - 어느 method가 A, B라는 checked exception만을 던진다고 선언되었다면 client code들은 이 예외만을 처리하거나 위로 전달하도록 작성된다. 나중에 이 method의 다음 버전에서 C라는 exception을 던질 필요가 생기면 client와의 contract이 깨지게 된다.
  4. Scalability - A, B, C, D라는 method들이 각각 4개씩의 checked exception을 던지고 U라는 method가 이 것들을 호출하는데 예외들을 처리하지 않는다면 U는 총 16개의 checked exception을 던진다고 선언해야 한다. 상위로 올라갈 수록 선언해야 할 exception의 개수는 기하급수적으로 늘어나게 된다.
등이 있습니다. 4번의 경우에는 각 레벨에 맞는 exception을 정의해서 사용하면 해결할 수는 있을 것 같습니다. 즉, A, B, C, D가 던지는 16개의 exception을 U가 던질 때는 자기의 context에 맞는 예외 두어개로 mapping하여 던진다는 식이지요.

암튼.. 그럼 왜 여지껏 저는 checked exception이 매우 그럴 듯해 보였던 걸까요? C#의 한 language designer가 이렇게 얘기했다네요.
Examination of small programs leads to the conclusion that requiring exception specifications could both enhance developer productivity and enhance code quality, but experience with large software projects suggests a different result -- decreased productivity and little or no increase in code quality.
하지만 몇가지 경우엔 checked exception이 유용할 수 있다고 합니다.
  • 예외가 significant boundary를 넘어가는 경우. 예를 들어 CORBA의 machine boundary같은... 이런 경우 좀 더 명시적인 예외 스펙이 도움이 된다.
  • package 내부에서 사용되나 절대 외부로 넘어가서는 안되는 예외의 경우 checked exception을 사용하면 컴파일러가 이를 감시하게 할 수 있다.

예외에 관해 참고할 만한 글들입니다.

Comments

  1. [...] Checked exception 관련 글들을 찾아 보다가 읽게 된 문서입니다. CLU라는 프로그래밍 언어를 개발하게 된 배경과 과정에 대한 내용인데 정말 재밌네요. 참고로 문서가 좀 길어보이지만 한 1/3은 부록입니다. [...]

    ReplyDelete

Post a Comment

Popular posts from this blog

CodeHighlighter plugin test page.

This post is for testing CodeHighlighter plugin which uses GeSHi as a fontifier engine. ((Those code blocks are acquired from Google Code Search .)) ((For more supported languages, go CodeHighlighter plugin or GeSHi homepage.)) C++ (<pre lang="cpp" lineno="1">) class nsScannerBufferList { public: /** * Buffer objects are directly followed by a data segment. The start * of the data segment is determined by increment the |this| pointer * by 1 unit. */ class Buffer : public PRCList { public: Buffer() { ++index_; } PHP (<pre lang="php" lineno="4">) for ($i = 0; $i $value = ord( $utf8_string[ $i ] ); if ( $value < 128 ) { // ASCII $unicode .= chr($value); } else { if ( count( $values ) == 0 ) { $num_octets = ( $value } $values[] = $value; Lisp (<pre lang="lisp">) ;;; Assignment (define-caller-pattern setq ((:star var fo...

C++ of the Day #43 - SQLite3 C++ wrapper #1

The Definitive Guide to SQLite 를 읽다가 공부 겸 해서 C++ wrapper를 만들어 보았습니다. 최대한 C++ 냄새(?)가 나도록 만들어 보았습니다. :-) ((SQLite는 복잡한 관리가 필요없이 사용가능한, 파일이나 메모리 기반의, 라이브러리로 제공되는, 약 250kb 용량의, 대부분의 SQL92문을 지원하는, open source RDB입니다.)) 이 wrapper를 사용하기 위해서는 (당연하게도!) sqlite3 와 (당연하게도?) boost 라이브러리가 필요합니다. 사용 예들을 살펴보는 것으로 설명을 대신합니다. 이번 글에서는 다음과 같은 contacts 테이블이 test.db에 존재한다고 가정합니다. CREATE TABLE contacts ( id INTEGER PRIMARY KEY, name TEXT NOT NULL, phone TEXT NOT NULL, UNIQUE(name, phone) ); Command 먼저 test.db 파일을 사용하기 위해 다음과 같이 파일 이름을 주어 connection 객체를 생성합니다. 생성과 동시에 test.db와 연결이 이루어집니다. ((생성자외에 open() 함수를 사용할 수도 있습니다.)) sqlite3pp::connection conn("test.db"); 다음은 contacts 테이블에 정보를 추가하는 가장 간단한 방법입니다. connection 클래스에서 제공하는 execute 함수를 사용합니다. ((executef 함수를 사용하면 printf와 같은 문법을 사용하여 query문을 작성할 수 있습니다.)) conn.execute("INSERT INTO contacts (name, phone) VALUES ('user', '1234')"); 위와 동일한 작업을 parameterized query를 사용하여 할 수도 있습니다. ((step()함수가 실제 query문을 수행하는 함수입니다. ...

Textiler plugin test page

This post is for testing Textiler plugin . This plugin uses Textile engine (version 2.0.0). The sample text is come from Textile test page. (Note that the result will be vary according to your CSS options.) Supported wiki syntax Rendering result h2{color:green}. This is a title h3. This is a subhead p{color:red}. This is some text of dubious character. Isn't the use of "quotes" just lazy writing -- and theft of 'intellectual property' besides? I think the time has come to see a block quote. bq[fr]. This is a block quote. I'll admit it's not the most exciting block quote ever devised. Simple list: #{color:blue} one # two # three Multi-level list: # one ## aye ## bee ## see # two ## x ## y # three Mixed list: * Point one * Point two ## Step 1 ## Step 2 ## Step 3 * Point three ** Sub point 1 ** Sub point 2 Well, that went well. How about we insert an <a href="/" title="watch out">old-fashioned hypertext link</a>? Will the quo...