try 블록
예외가 예상되는 부분에 작성
except 블록
에외발생 시 처리를 담당하는 부분
else 블록
예외가 발생하지 않은 경우 수행
finally 블록
예외발생과 상관 없이 수행
>>> def divide(a, b):
return a/b
>>> try:
c = divide(5, 0)
except:
print("Exception is occured!!")
Exception is occured!!
처리할 예외를 명시 할 수 있다.
>>> def divide(a, b):
return a/b
>>> try:
c = divide(5, 'string')
except ZeroDivisionError:
print('ZeroDivisonError.')
except TypeError:
print("TypeError")
except:
print("I don't know Error")
TypeError
두 경우가 아닌 경우 except 구문을 통해 처리
예외 처리는 반드시 좁은 범위에서 넓은 범위로 확장해야 한다.
>>> def divide(a, b):
return a/b
>>> try:
c = divide(5, 'string')
except Exception: << 모든 에러에 대해 이 부분에서 처리
print("I don't know Error")
except ZeroDivisionError:
print('ZeroDivisonError.')
except TypeError:
print("TypeError")
I don't know Error
else와 finally 예제
>>> def devide(a, b):
return a/b
>>> try:
c = divide(5, 2)
except ZeroDivisionError:
print("ZeroDivisionError.")
except TypeError:
print("TypeError.")
except:
print("No ZeroDivisionError, TypeError.")
else: << 예외가 발생하지 않는 경우
print("Result: {0}".format(c))
finally: << 예외 발생 여부와 상관없이 수행
print("always perform finally block.")
Result: 2.5
always perform finally block.
예외에 대한 정보를 전달받는 예제
>>> def divide(a, b)
SyntaxError: invalid syntax
>>> def divide(a, b):
return a/b
>>> try:
c = divide(5, "af")
except TypeError as e:
print("Error: ", e.args[0])
except Exception:
print("I don't know")
Error: unsupported operand type(s) for /: 'int' and 'str'
에러를 묶어서 처리하는 예제
>>> def divide(a, b):
return a/b
>>> try:
c = divide(5, 0)
except (ZeroDivisionError, OverflowError, FloatingPointError):
print("operation Error")
except TypeError:
print("No Digit")
except Exception:
print("I don't know")
operation Error
상위클래스를 처리할 때 하위의 모든 클래스도 이부분에서 처리
>>> def divide(a, b):
return a/b
>>> try:
c = divide(5,0)
except ArithmeticError:
print("ArithmeticError.")
except TypeError:
print("TypeError.")
except Exception:
print("Exception.")
ArithmeticError.
try ~ finally 구문
>>> FilePath = './test.txt'
>>> try:
f = open(FilePath, 'r')
try:
data = f.read(128)
print(data)
finally:
f.close()
except IOError:
print("Fail to open {0} file".format(FilePath))
Fail to open ./test.txt file
예외 발생 여부와 상관 없이 열린 파일을 finally 블록에서 닫음