예외란 문법적인 문제는 없지만, 실행 중 발생하는 예상하지 못한 문제이다.
예외와 에러는 다르다.
예외에 있어서 최상위 클래스는 EXCEPTION이다.
예외 처리는 발생된 예외를 별도로 처리함으로써 프로그램 전체의 실행에 문제가 없도록(=시스템 흐름에 방해가 되지 않게 하기위해) 하는 것.
try ~ except 로 예외 발생 예상 구문을 감싸주면 된다.
nums = []
n = 1
while n < 6:
try:
num = int(input('enter number :'))
except: #숫자가 아닌 자료형이 입력되면 예외처리.
print('exception~!!')
continue #
nums.append(num)
n += 1
print(f'nums : {nums}')
#출력
enter number :33
enter number :1
enter number :6
enter number :8
enter number :a
exception~!!
enter number :asdg
exception~!!
enter number :asdf
exception~!!
enter number :3
nums : [33, 1, 6, 8, 3]
else는 예외가 발생하지 않은 경우 실행하는 구문.
finally는 예외 발생과 상관없이 항상 실행한다.
예외를 담당하는 클래스. 코드에 작성시, 예외처리된 내용을 출력해준다.
num1 = int(input('num1 입력 : '))
num2 = int(input('num2 입력 : '))
try:
print(f'num1 / num2 = {num1 / num2}')
except Exception as e: #Exception클래스 사용
print(f'exception : {e}')
print(f'num1 * num2 = {num1 * num2}')
print(f'num1 - num2 = {num1 - num2}')
print(f'num1 + num2 = {num1 + num2}')
num1 입력 : 10
num2 입력 : 0
exception : division by zero #예외처리된 내용까지 보여준다.
num1 * num2 = 0
num1 - num2 = 10
num1 + num2 = 10
Exception 클래스를 상속해서 유저가 임의대로 예외 클래스를 만들 수 도 있다.
class PwShortException(Exception): # 패스워드 길이 미달 예외처리
def __init__(self, str):
super().__init__(f'{str} : 길이 5 미만!!')
class PwLongException(Exception): # 패스워드 길이 초과 예외처리
def __init__(self, str):
super().__init__(f'{str} : 길이 10 초과!!')
class PwWrongException(Exception): # 패스워드 불일치 예외처리
def __init__(self, str):
super().__init__(f'{str} : Password 틀림!!')
adminPw = input('enter Admin Password : ')
try:
if len(adminPw) < 5:
raise PwShortException(adminPw)
elif len(adminPw) > 10:
raise PwLongException(adminPw)
elif adminPw != 'admin1234':
raise PwWrongException(adminPw)
elif adminPw == 'admin1234':
print('확인!!')
except PwShortException as e1:
print(e1)
except PwLongException as e2:
print(e2)
except PwWrongException as e3:
print(e3)
#출력 모든 예외처리 작동 OK
enter Admin Password : 123
123 : 길이 5 미만!!
enter Admin Password : 123
123 : 길이 5 미만!!
enter Admin Password : admin12
admin12 : Password 틀림!!
enter Admin Password : admin1234
확인!!