키워드 를 제외한 파이썬
예시
명령문에서 오류가 발생하면 "Something was wrong"이 인쇄됩니다.
try:
x > 3
except:
print("Something went wrong")
정의 및 사용
키워드 는 except
try...except 블록에서 사용됩니다. try 블록에서 오류가 발생하면 실행할 코드 블록을 정의합니다.
서로 다른 오류 유형에 대해 서로 다른 블록을 정의하고 아무 문제가 없는 경우 실행할 블록을 정의할 수 있습니다. 아래 예를 참조하십시오.
더 많은 예
예시
NameError이면 하나의 메시지를 작성하고 TypeError이면 다른 메시지를 작성하십시오.
x = "hello"
try:
x > 3
except NameError:
print("You have a variable that is not defined.")
except TypeError:
print("You are comparing values of different type")
예시
오류를 발생시키는 문을 실행하려고 시도하지만 정의된 오류 유형(이 경우 ZeroDivisionError)은 없습니다.
try:
x = 1/0
except NameError:
print("You have a
variable that is not defined.")
except TypeError:
print("You
are comparing values of different type")
except:
print("Something else went wrong")
예시
오류가 발생하지 않은 경우 메시지를 작성합니다.
x = 1
try:
x > 10
except NameError:
print("You have a variable that is not defined.")
except TypeError:
print("You are comparing values of different type")
else:
print("The 'Try' code was executed without raising any errors!")
관련 페이지
try
키워드 .
finally
키워드 .