파이썬/예외처리
파이썬 예외처리
watervin
2022. 1. 11. 11:01
예외처리
try :
실행할 명령
except 예외 as 변수:
오류처리문
else :
예외가 발생하지 않았을 떄의 처리
str = "89점"
try:
score = int(str)
print(score)
except:
print("예외가 발생했습니다.")
print("작업완료")
|
while True:
str = input("점수를 입력하세요 : ")
try :
score = int(str)
print("입력한 점수 : ",score)
break
except:
print("점수형식이 잘못되었습니다.")
print("작업완료")
|
str = "89"
try:
score= int(str)
print(score)
a = str[5]
except (ValueError,IndexError):
print("점수의 형식이나 첨자가 잘못되었습니다.")
print("작업완료")
|
str = "89"
try:
score= int(str)
print(score)
except ValueError as e:
print(e)
except IndexError as e:
print(e)
print("작업완료")
|
def calcsum (n):
if n<0:
raise ValueError
total = 0
for i in range(n+1):
total += i
return total
try:
print("~10 =", calcsum(10))
print("~5 =", calcsum(-5))
except ValueError:
print("입력값이 잘못되었습니다.")
calcsum()
|
assert
assert 조건, 메세지
조건이 true면 통과
false면 메세지를 가지는 예외 발생
def main():
try:
score = 128
assert score <= 100, "점수는 100이하여야합니다"
print(score)
except Exception as e:
print(e)
main()
|