---
id: python-try-except
title: "Python Try Except"
category: "Programming_Language"
status: "draft"
verification_status: "conceptual"
canonical_id: ""
aliases: ["exception handling", "raise", "finally", "파이썬 예외 처리"]
duplicate_of: ""
source_trust_level: "B"
confidence_score: 0.9
created_at: 2026-07-04
updated_at: 2026-07-04
review_reason: ""
merge_history: []
tags: ["python", "programming", "w3schools", "exceptions", "try-except"]
raw_sources: ["https://www.w3schools.com/python/python_try_except.asp"]
applied_in: []
github_commit: ""
---

# [[Python Try Except]]

## 🎯 한 줄 통찰 (One-line insight)
try/except/else/finally each answer a distinct question — try (what might fail), except (what to do on failure), else (what to do on success), finally (what must ALWAYS run) — and finally is what guarantees cleanup like closing a file even when an error occurs. [S1]

## 🧠 핵심 개념 (Core concepts)
- **`try`** — tests a block of code for errors. [S1]
- **`except`** — handles the error if the try block raises one. [S1]
- **`else`** — runs only if the try block raised NO error. [S1]
- **`finally`** — runs regardless of whether an error occurred. [S1]
- **Multiple except blocks** — catch different error types differently (e.g. `except NameError:` vs. bare `except:`). [S1]
- **`raise`** — explicitly throws an exception, optionally with a specific type (`TypeError`, custom `Exception`) and message. [S1]

## 🧩 추출된 패턴 (Extracted patterns)
- **finally for resource cleanup** — the canonical example opens a file inside try, writes inside a nested try/except, and uses `finally: f.close()` to guarantee the file handle closes even if the write fails — the program never leaves a file open. [S1]

## 📖 세부 내용 (Details)
- Basic exception handling: `try: print(x) except: print("An exception occurred")`. [S1]
- Multiple except types: `try: print(x) except NameError: print("Variable x is not defined") except: print("Something else went wrong")`. [S1]
- else on success: `try: print("Hello") except: ... else: print("Nothing went wrong")`. [S1]
- finally for cleanup: [S1]
```python
try:
    f = open("demofile.txt")
    try:
        f.write("Lorum Ipsum")
    except:
        print("Something went wrong when writing to the file")
    finally:
        f.close()
except:
    print("Something went wrong when opening the file")
```
- Raising a custom exception: `x = -1; if x < 0: raise Exception("Sorry, no numbers below zero")`. [S1]
- Raising a typed exception: `if not type(x) is int: raise TypeError("Only integers are allowed")`. [S1]

## ⚖️ 모순 및 업데이트 (Contradictions & updates)
소스에서 모순되는 정보는 발견되지 않음.

## 🛠️ 적용 사례 (Applied in summary)
현재 발견된 실제 적용 사례가 없습니다 — Python User Input 챕터에서 이 예외 처리가 사용자 입력 검증 루프에 직접 적용된다. [S1]

## 💻 코드 패턴 (Code patterns)
finally guarantees cleanup (Python):
```python
try:
    f = open("demofile.txt")
    try:
        f.write("Lorum Ipsum")
    except:
        print("Something went wrong when writing to the file")
    finally:
        f.close()
except:
    print("Something went wrong when opening the file")
```

## ✅ 검증 상태 및 신뢰도
- **상태:** draft
- **검증 단계:** conceptual
- **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body)
- **신뢰 점수:** 0.90
- **중복 검사 결과:** 신규 생성 (New discovery)

## 🔗 지식 그래프 (Knowledge Graph)
- **상위/루트:** [[Python Tutorial]]
- **관련 개념:** [[Python User Input]], [[Python File Handling]]
- **참조 맥락:** 오류 처리의 표준 패턴 — 사용자 입력 검증, 파일 자원 정리에 직접 적용된다.

## 📚 출처 (Sources)
- [S1] W3Schools — Python Try Except — https://www.w3schools.com/python/python_try_except.asp

## 📝 변경 이력 (Change history)
- 2026-07-04: Initial draft synthesized from the W3Schools "Python Try Except" page (Astra wiki-curation, P-Reinforce v3.1 format).
