C.W.K.
Stream
Lesson 09 of 10 · published

에러 처리 — sqlite3 Exception 클래스

~10 min · python, errors, exceptions

Level 0Scout
0 XP0/80 lessons0/10 achievements
0/120 XP to next level120 XP to go0% complete

옳은 거 catch, 세상 다 X

sqlite3 모듈이 작은 exception 계층 raise. 알면 expected failure (제약 위반, locked DB) 를 모든 거 catch 안 하고 처리.

  • sqlite3.Error — 모든 거의 base.
  • sqlite3.DatabaseError — 엔진 안의 모든 거.
  • sqlite3.IntegrityError — 제약 위반 (UNIQUE, NOT NULL, FK, CHECK).
  • sqlite3.OperationalError — 운영 이슈 (locked, malformed, disk full).
  • sqlite3.ProgrammingError — 사용 에러 (closed cursor, 잘못된 param 수).
  • sqlite3.InterfaceError — SQLite 보기 전 driver-side 문제.
Tip: except sqlite3.IntegrityError 가 collide 가능 INSERT 의 'duplicate key' idiomatic 처리. UPSERT (track 4) 와 합치면 대부분 앱이 catch site 거의 없음.

Code

올바른 exception catch·python
import sqlite3

try:
    conn.execute('INSERT INTO users(email) VALUES (?)', ('dup@x.com',))
except sqlite3.IntegrityError as e:
    print('duplicate 또는 다른 제약 실패:', e)
except sqlite3.OperationalError as e:
    print('운영 이슈 (locked, disk 등):', e)
except sqlite3.DatabaseError as e:
    print('엔진의 다른 거:', e)

External links

Exercise

각 exception 클래스 일부러 trigger: IntegrityError (UNIQUE 위반), OperationalError (없는 테이블 open), ProgrammingError (closed cursor 사용). 각각 다른 거 안 삼키고 specific 케이스 처리하는 tight except. 어느 게 user-facing 에러 메시지 적합, 어느 게 log 만 적합인지 생각.

Progress

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

댓글 0

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

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