try:
실행코드
except:
대체코드
• try의 코드를 실행중 에러가 발생하면 바로 except의 코드를 실행하게 된다
✔️ 특정 예외만 처리하기
try:
실행코드
except 예외이름:
대체코드
○ 크게 Exception 안에 여러종류의 에러가 있다.
• StopIteration
• ArithneticError
-> ZeroDivisionError
• LookUpError
-> IndexError
• SyntaxError
등
except Exception as e:
print('error', e)
try:
실행코드
except:
예외 발생시 코드
else:
예외 미발생시 코드
finally:
예외와 상관없이 항상 실행할 코드
• esle는 except 바로 다음에 와야하고 except를 생략할 수 없다.
try:
...
if x != 0:
raise Exception("x는 0이 아닙니다.")
except Exception as e:
print('예외가 발생했습니다.', e)
• 아래와 같은 형태로도 사용가능하다.
def 함수이름():
x = int(input())
if x!=0:
raise Exception("x는 0이 아닙니다.")
try:
함수이름()
except Exception as e:
print('예외가 발생했습니다.', e)
def check_zero():
try:
x = int(input())
if x%3 != 0:
raise Exception('not 0')
print(x)
except Exception as e:
print('def error', e)
raise
try:
check_zero()
except Exception as e:
print('script error', e)
def error not 0
script error not 0
class 예외이름(Exception):
def __init__(self):
super().__init__('에러메시지')