
νλ‘κ·Έλ¨μ νμ μ°λ¦¬κ° μλν μ λ ₯λ§ λ°μ§ μλλ€. μ«μλ₯Ό κΈ°λνλλ° λ¬Έμκ° λ€μ΄μ€κ±°λ, νμΌμ΄ μ‘΄μ¬νμ§ μκ±°λ, 0μΌλ‘ λλλ μν©μ΄ μΈμ λ λ°μν μ μλ€.
μ΄λ° μν©μμ νλ‘κ·Έλ¨μ΄ λ°λ‘ μ’ λ£λλ€λ©΄ μ¬μ©μλ λΉν©νκ³ , μλΉμ€λ λΆμμ ν΄μ§λ€. μμΈ μ²λ¦¬λ νλ‘κ·Έλ¨μ μμ μ±μ μ± μμ§λ μμ λ§μ΄λ€.
try:
result = 10 / 0
except ZeroDivisionError:
print("μλ¬: 0μΌλ‘ λλ μ μμ΅λλ€")
μ μ½λμ²λΌ μμΈλ₯Ό μ²λ¦¬νλ©΄, νλ‘κ·Έλ¨μ μ£½μ§ μκ³ λ€μ λ‘μ§μ κ³μ μνν μ μλ€.
μ€λ¬΄μμ μμΈ μ²λ¦¬κ° μλ μ½λ = μνν μ½λλ€.
try:
# λ¬Έμ κ° λ°μν μ μλ μ½λ
except νΉμ μμΈ as e:
# ν΄λΉ μμΈ μ²λ¦¬
except Exception as e:
# λͺ¨λ μμΈ μ²λ¦¬
else:
# μμΈκ° λ°μνμ§ μμμ λλ§ μ€ν
finally:
# μμΈ μ¬λΆμ μκ΄μμ΄ νμ μ€ν
| κ΅¬λΆ | μ€λͺ |
|---|---|
| Error | λ¬Έλ² μ€λ₯ λ± νλ‘κ·Έλ¨ μ€ν μμ²΄κ° λΆκ°λ₯ν μν |
| Exception | μ€ν μ€ λ°μνμ§λ§ μ²λ¦¬ κ°λ₯ |
# Error (μ€ν λΆκ°)
if True
print("error")
# Exception (μ²λ¦¬ κ°λ₯)
10 / 0
| μμΈ | λ°μ μν© |
|---|---|
| ValueError | μλͺ»λ κ° |
| TypeError | νμ λΆμΌμΉ |
| ZeroDivisionError | 0μΌλ‘ λλκΈ° |
| FileNotFoundError | νμΌ μμ |
| IndexError | μΈλ±μ€ μ΄κ³Ό |
| KeyError | λμ λ리 ν€ μμ |
λ Όλ¦¬μ μΌλ‘ μλͺ»λ μν©μ΄μ§λ§, νμ΄μ¬μ΄ μλμΌλ‘ μλ¬λ₯Ό λ΄μ£Όμ§ μλ κ²½μ°λ μλ€. μ΄λ΄ λ raiseλ₯Ό μ¬μ©νλ€.
def divide(a, b):
if b == 0:
raise ValueError("bλ 0μ΄ λ μ μμ")
return a / b
μ€λ¬΄μμλ μλ―Έ μλ μλ¬λ₯Ό λ§λ€κΈ° μν΄ μ§μ μμΈ ν΄λμ€λ₯Ό μ μνλ€.
class InsufficientBalanceError(Exception):
pass
class BankAccount:
def __init__(self, balance):
self.balance = balance
def withdraw(self, amount):
if amount > self.balance:
raise InsufficientBalanceError("μμ‘ λΆμ‘±")
self.balance -= amount
μ΄λ κ² νλ©΄ μλ¬ λ©μμ§ μμ²΄κ° λ¬Έμ μν μ νκ² λλ€.
νμΌμ μΈμ λ μμ μ μκ³ , μ΄λ€κ° μ€ν¨ν μ μλ€.
try:
f = open("data.txt", "r")
data = f.read()
except FileNotFoundError:
print("νμΌμ΄ μμ΅λλ€")
finally:
f.close()
withλ νμΌμ μμ νκ² κ΄λ¦¬νκΈ° μν νμ λ¬Έλ²μ΄λ€.
with open("data.txt", "r", encoding="utf-8") as f:
data = f.read()
| λͺ¨λ | μλ―Έ |
|---|---|
| r | μ½κΈ° |
| w | μ°κΈ° (κΈ°μ‘΄ μμ ) |
| a | μΆκ° |
| rb / wb | λ°μ΄λ리 |
import csv
with open("students.csv", "r", encoding="utf-8") as f:
reader = csv.reader(f)
for row in reader:
print(row)
import json
data = {"name": "Kim", "age": 20}
with open("config.json", "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False, indent=2)