[μ 보] νμ΄μ¬ μμΈμ²λ¦¬ μ¬λ¬κ° νκΈ°
νμ΄μ¬μμλ try-catch λ¬Έμ μ¬μ©νμ¬ μμΈ μ²λ¦¬λ₯Ό ν μ μμ΅λλ€. λ€μμ try-catch λ¬Έμ μ¬μ©νμ¬ μ¬λ¬λ² μμΈλ₯Ό μ²λ¦¬νλ μ½λμ λλ€.
try:
# μμΈ λ°μ κ°λ₯ν μ½λ
result = some_function()
except ValueError:
# ValueError μμΈ μ²λ¦¬
print("ValueError occurred")
except IndexError:
# IndexError μμΈ μ²λ¦¬
print("IndexError occurred")
except Exception as e:
# κ·Έ μΈ λͺ¨λ μμΈ μ²λ¦¬
print("An error occurred:", e)
finally:
# μμΈ λ°μ μ¬λΆμ μκ΄μμ΄ μ€νλλ μ½λ
print("Execution complete")
μ μ½λμμλ try λΈλ‘ μμμ some_function() ν¨μλ₯Ό νΈμΆνκ³ , μ΄ ν¨μμμ λ°μν μ μλ μ¬λ¬ κ°μ§ μμΈλ€μ μ²λ¦¬ν©λλ€. λ§μ½ some_function() ν¨μκ° ValueError μμΈλ₯Ό λ°μμν€λ©΄ except ValueError λΈλ‘μ΄ μ€νλκ³ , IndexError μμΈκ° λ°μνλ©΄ except IndexError λΈλ‘μ΄ μ€νλ©λλ€. κ·Έ μΈ λͺ¨λ μμΈλ€μ except Exception λΈλ‘μμ μ²λ¦¬λλ©°, finally λΈλ‘μ μμΈ λ°μ μ¬λΆμ μκ΄μμ΄ νμ μ€νλ©λλ€.
μ΄μ κ°μ λ°©μμΌλ‘ μ¬λ¬ μμΈλ₯Ό μ²λ¦¬νλ κ²μ΄ κ°λ₯ν©λλ€. λ¨, μμΈ μ²λ¦¬λ λ무 λ§μ΄ νλ κ²λ³΄λ€λ μ μ ν μμ€μΌλ‘ νλ κ²μ΄ μ’μ΅λλ€. λΆνμν μμΈ μ²λ¦¬λ μ½λμ κ°λ μ±μ λ¨μ΄λ¨λ¦΄ λΏλ§ μλλΌ, μμΈ μ²λ¦¬κ° λ무 λ§μ΄ λμ΄μμ κ²½μ° νλ‘κ·Έλ¨μ΄ λ λλ €μ§ μλ μμ΅λλ€.