try/except 구문
def return_elem_or_minus_one(index):
short_list = [1, 2, 3]
elem = 0
try:
elem = short_list[index]
print("이 문장은 exception이 발생되면 실행되지 않습니다!")
except IndexError:
print(f"이 문장은 Exception이 발생하면 실행 됩니다")
elem = -1
else:
print("이 문장은 exception 발생 하지 않았을 때 실행됩니다!")
finally:
print("이 문장은 exception 발생 여부와 상관없이 무조건 실행됩니다!")
print(elem)
return elem
try :
- 구문에서 발생하는 Exception을 핸들하기 위한 문법
except Exception as e :
- try 구문에서 Exception객체에 해당하는 exception이 발생했을 경우 해당 구문을 실행함
- 객체 e에 Exception 객체 return
else:
- try 구문에서 규정한 Exception이 발생하지 않았을 경우 실행되는 구문
finally:
- try 구문에서 규정한 Exception의 발생 여부에 관계 없이 실행되는 구문
Raise
if 조건:
raise UserDefinedError
- 사용자가 구현한 Exception 객체를 발생시키는 기능
사용자 정의 에러
class Error(Exception):
"""Base class for exceptions in this module."""
pass
class InputError(Error):
"""Exception raised for errors in the input.
Attributes:
expression -- input expression in which the error occurred
message -- explanation of the error
"""
def __init__(self, expression, message):
self.expression = expression
self.message = message