Python Exception

Hyunwoo Lee·2022년 3월 14일
0
try:
	예외 발생 가능 코드
except <Exception Type>:
	예외 발생시 대응하는 코드

if else 문으로 처리해도 되지만
예외처리를 권장하는 경우 있음
ex)

for i in range(10):
	try:
    	print(10/i)
    except ZeroDivisionError:
    	print("Not divided by 0")

ZeroDivisionError 는 built in error이다.

Exception을 잡으면 자동으로 종료되지 않고 위로 올라가 다시 수행한다. 수행한다.
IndexError, NameError, ZeroDivisionError, ValueError등이 있다.

Exception은 모든 에러를 잡는다.
as ...를 이용하면 ...에 에러 내용을 담을 수 있다.

a = range(5)
for i in range(10):
    try:
        print(a[i])
        print(v)
    except IndexError as e:
        print(e)
    except Exception as e:
        print(e)
0
name 'v' is not defined
1
name 'v' is not defined
2
name 'v' is not defined
3
name 'v' is not defined
4
name 'v' is not defined
range object index out of range
range object index out of range
range object index out of range
range object index out of range
range object index out of range
try:

except:

else:

finally:

이런식으로 짤 수도 있다.
문제가 있으면 except, 없으면 else, 그리고 무조건 finally를 실행

하지면 if문은 logic적인 문제를 다룰 때 사용하는걸 권장
except는 처리가 잘못된 경우에 사용.

raise

raise <Exception Type> # 예외정보

의도적으로 Exception을 일으키기 위해 사용

while True:
    value = "012345"
    for digit in value:
        if digit not in "0123":
            raise ValueError("0123에 속하지 않음")
        print("정수값", int(digit))

특정 조건이 아닐 때 에러 발생시키기

assert isinstance(a, int)

a가 int값이 아니면 에러 발생

profile
10분만 쉬어요

0개의 댓글