예외(exception) 처리 구문에 대해 알아봅니다.
try:
# 실행할 코드
except:
# optional block
# exception 발생 시 실행할 코드
else:
# exception이 없는 경우 수행할 코드
finally:
# 실행할 코드
# 이 부분의 코드는 예외 상황 발생 여부에 상관없이 실행됨!
def divide(x, y):
try:
result = x // y
except ZeroDivisionError:
print("Error: You are dividing by zero")
else:
print("Your answer is :", result)
finally:
print('This is always executed')
print("case 1")
print(divide(1, 2))
print("case 2")
print(divide(1, 0))
def learnfinally():
try:
print("Inside try Block")
return 1
except Exception as e:
print(e)
finally:
print("Inside Finally")
print(learnfinally())
finally 구문이 return 구문보다 먼저 실행되는 것을 확인할 수 있습니다.
try-except 구문으로 if 구문을 대체할 수 있습니다.
import timeit
code_snippets =["""\
try:
result = 100000 / value
except ZeroDivisionError:
pass""",
"""\
if value:
result = 100000 / value""",
]
for value in (1, 0):
for code in code_snippets:
t = timeit.Timer(stmt = code, setup ='value ={}'.format(value))
print("----------------------")
print("value = {}\n{}".format(value, code))
print("%.2f usec / pass\n" % (1000000 * t.timeit(number = 100000)/100000))
exception이 발생하지 않을 때는, try-except 구문의 수행속도가 더 빠른 것을 확인할 수 있습니다.
exception이 발생할 확률이 50%이상이라면, if 구문을 사용하는 게 나을 수도 있습니다.
필요한 경우, 강제로 exception을 발생시키는 구문입니다.
raise Exception("exception context")
x = -1
if x < 0:
print("Your input:", x)
raise Exception("Sorry, negative numbers are not allowed")
특정 조건이 만족하지 않을 경우 exception을 발생시킵니다.
assert Expression[, Arguments]
def KelvinToFahrenheit(Temperature):
print(f"input: {Temperature}")
assert (Temperature >= 0),"Colder than absolute zero!"
return ((Temperature-273)*1.8)+32
print (KelvinToFahrenheit(273))
print (KelvinToFahrenheit(-5))
참고문헌