Exception
Exception이란 예외상황이란 뜻인데요, 내가 코드를 작성하는데 의도치않게 오류가 날때가 있을 때 쓰는 코드인것 같습니다.
def ecexption_func(index):
a_list = [1, 2, 3]
print(a_list[index])
ecexption_func(3)
# error => IndexError: list index out of range
Eception Handling : try 구문을 활용함
def ecexption_func(index):
a_list = [1, 2, 3]
try:
print(a_list[index])
except Exception: # 에러가 낫을때 실행되는 구문
print("에러가 났습니다.")
finally: # 에러가나거나 나지않거나 실행되는 구문
print("에러상관없이 나타납니다.")
ecexption_func(3)
Exception이 발생하면, 발생한 코드 위치에서 다음 코드들이 실행되지 않고 바로 프로그램이 종료하게됩니다.
하지만 exception이 발생해도 해당 프로세스가 종료하지 않고 대신 다른 로직을 실행하게 한 후 프로그램을 계속 실행하게 하는데
이것을 exception handling이라고 합니다.
Exception은 여러 exception을 catch할 수 있습니다.
def ecexption_func(index):
a_list = [1, 2, 3]
try:
print(a_list[index])
except IndexError: # index error에 한해 실행시키는 구문
print("index error가 났습니다.")
except Exception: # 다른exception이 났을때 행해지는 구문
print("다른 에러가 났습니다.")
finally:
print("에러상관없이 나타납니다.")
ecexption_func("afa")
그리고 try문에서 esle도 사용가능하다~
def ecexption_func(index):
a_list = [1, 2, 3]
try:
print(a_list[index])
except IndexError:
print("index error가 났습니다.")
except Exception:
print("다른 에러가 났습니다.")
else:
print("no exeption")
finally:
print("에러상관없이 나타납니다.")
ecexption_func("afa")
'Python' 카테고리의 다른 글
Iterator (0) | 2020.06.04 |
---|---|
Python Assignment (List comprehension) (0) | 2020.06.04 |
Modules and Package (Feature) (0) | 2020.06.03 |
Modules and Package (0) | 2020.06.02 |
Class (0) | 2020.06.01 |