# 간단한 함수를 하나 만든다.
def exceptionHandling():
a = 10
b = 2
c = (a / b)
print(c)
exceptionHandling()
# 결과
5.0
# 0으로 나누기 에러를 만들어 본다.
def exceptionHandling():
a = 10
b = 0
c = (a / b)
print(c)
exceptionHandling()
# 결과
ZeroDivisionError: division by zero
# 타입 에러를 만들어 본다.
def exceptionHandling():
a = 10
b = "string"
c = (a / b)
print(c)
exceptionHandling()
# 결과
TypeError: unsupported operand type(s) for /: 'int' and 'str'
# 타입 에러에 대한 예외 처리를 만든다.
def exceptionHandling():
try:
a = 10
b = "string"
c = (a / b)
print(c)
except TypeError:
print("Can't divide by string ")
exceptionHandling()
# 결과
Can't divide by string
# 0으로 나누기 에러에 대한 예외 처리를 만든다.
def exceptionHandling():
try:
a = 10
b = 0
c = (a / b)
print(c)
except TypeError:
print("Can't divide by string ")
except ZeroDivisionError:
print("Zero Division")
exceptionHandling()
# 결과
Zero Division
# 에러에 대한 공통 예외 처리를 만든다.
def exceptionHandling():
try:
a = 10
b = 0
c = (a / b)
print(c)
except:
print("In the except block")
exceptionHandling()
# 결과
In the except block
# 또 다른 에러에 대해 공통 예외 처리가 적용되는지 확인한다.
def exceptionHandling():
try:
a = 10
b = "string"
c = (a / b)
print(c)
except:
print("In the except block")
exceptionHandling()
# 결과
In the except block
# 에러가 없을 경우 실행하는 로직을 정의할때
def exceptionHandling():
try:
a = 10
b = 2
c = (a / b)
print(c)
except:
print("In the except block")
else:
print("Because there was no exception, else is executed")
exceptionHandling()
# 결과
5.0
Because there was no exception, else is executed
# 에러가 있던, 없든 간에 무조건 실행하는 로직을 정의할때
## 에러 없을 경우
def exceptionHandling():
try:
a = 10
b = 2
c = (a / b)
print(c)
except:
print("In the except block")
else:
print("Because there was no exception, else is executed")
finally:
print("Finally, always executed")
exceptionHandling()
# 결과
5.0
Because there was no exception, else is executed
Finally, always executed
## 에러 있을 경우
def exceptionHandling():
try:
a = 10
b = 0
c = (a / b)
print(c)
except:
print("In the except block")
else:
print("Because there was no exception, else is executed")
finally:
print("Finally, always executed")
exceptionHandling()
# 결과
In the except block
Finally, always executed
# 예외 문구를 담는 변수 이용
t = (1, 2, 3)
try:
t.append(4)
except AttributeError as e:
print("Error formed: ", e)
# 결과
Error formed: 'tuple' object has no attribute 'append'
댓글 영역