C.W.K.
Stream
Lesson 01 of 06 · published

try / except / else / finally — 4 절 다

~20 min · try, except, else, finally

Level 0호기심
0 XP0/93 lessons0/23 achievements
0/100 XP to next level100 XP to go0% complete

4 절 모양

Python 의 예외 처리 — try, except, else, finally 4 절. 대부분 코드는 try/except 만 — 나머지 둘은 특정 상황에서 값어치. elsetry 가 raise 없이 성공했을 때 실행. finally 는 항상 실행, 예외 여부 무관 — 반드시 일어나야 할 정리에 사용.

왜 별도 else 절

try 본문 다음 코드를 try 블록 안에 두면 except 가 잡을 범위 넓어져 — 거기 버그도 조용히 잡혀. 같은 코드를 else 에 두면 except 가 진짜 위험한 것만 잡고, "다 잘됐어, 다음 단계" 로직이 분리. 작은 명료화, 진짜 버그 예방.

여러 예외 타입 잡기

타입 tuple — except (ValueError, TypeError):. 여러 except 절 가능 — 순서대로 체크, 첫 매치 이김. 예외 객체 바인딩도 — except ValueError as e:.

Bare except 는 거의 항상 잘못

except: (타입 없이) 가 *모든 거* 잡아 — KeyboardInterrupt (Ctrl+C) 와 SystemExit 포함. 그것들에 응답해야 할 코드가 조용히 삼킴. 가장 넓게 가도 except Exception, 이상적으론 기대하는 특정 타입.

원칙: 회복 가능한 실패 모드 처리하는 가장 좁은 예외 타입 잡아. 너무 넓게 = 의도 안 한 버그 숨김. 너무 좁게 = 진짜 실패 미처리. 적절한 grain 은 연산에 따라 — 디폴트 Exception 보다 특정 타입.

Code

try / except / else / finally — 4 절 다·python
def parse_int(s):
    try:
        result = int(s)
    except ValueError:
        print("파싱 못 함")
        return None
    else:
        print("파싱 성공")
        return result
    finally:
        print("항상 실행 (cleanup, logging 등)")

print(parse_int("42"))
# 파싱 성공
# 항상 실행 (cleanup, logging 등)
# 42

print(parse_int("숫자 아님"))
# 파싱 못 함
# 항상 실행 (cleanup, logging 등)
# None
여러 except — 첫 매치 이김·python
def lookup(d, key):
    try:
        return int(d[key])
    except KeyError:
        return f"키 {key!r} 없음"
    except ValueError:
        return f"키 {key!r} int 아님"
    except TypeError:
        return f"d 가 dict 아님"

print(lookup({"a": "42"}, "a"))      # 42
print(lookup({"a": "42"}, "b"))      # 키 'b' 없음
print(lookup({"a": "x"}, "a"))       # 키 'a' int 아님
print(lookup(None, "a"))             # d 가 dict 아님

# 타입 tuple — 한 except 가 여러 처리
try:
    pass
except (KeyError, ValueError) as e:
    print(type(e).__name__, e)
왜 else 가 도움 — except 가 보는 거 좁힘·python
# else 없이 — 위험
def bad(file_path):
    try:
        with open(file_path) as f:
            data = f.read()
            print("파일 크기:", len(data))      # 이게 실패하면 except 가 잡음
            value = int(data)                    # 이것도
    except FileNotFoundError:
        print("파일 없음")
    except ValueError:
        print("잘못된 숫자")
    # print() 또는 len() 의 버그도 잡힘 — 조용히 삼킴

# else 로 — except 가 진짜 위험한 연산만 잡음
def good(file_path):
    try:
        with open(file_path) as f:
            data = f.read()
    except FileNotFoundError:
        print("파일 없음")
        return
    else:
        print("파일 크기:", len(data))
        value = int(data)                       # 이게 실패하면 안 잡힘
        return value
Bare except — 거의 항상 잘못·python
# 안 좋음
try:
    risky()
except:                       # bare except
    pass                      # Ctrl+C 포함 모든 거 삼킴

# 좋음 — Exception 이 가장 넓은 합리적
try:
    risky()
except Exception as e:
    print("잡음:", type(e).__name__, e)

# 더 좋음 — 진짜 기대하는 거로 좁힘
try:
    risky()
except (ValueError, KeyError) as e:
    print("기대된 실패:", e)
# 다른 예외는 위로 전파 — 그게 맞음

External links

Exercise

함수 safe_divide(a, b)a / b 반환, 단 — TypeError 잡고 ("bad types" 문자열 반환), ZeroDivisionError 잡고 (a > 0 면 float('inf'), a < 0 면 float('-inf'), a == 0 면 0.0), else 로 'success' 출력 후 반환, finally 로 'attempted' 출력. 정상 / 0 으로 나누기 / 잘못된 타입 포함 최소 4 입력 조합 테스트.

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.