28
<예외발생 유형 1 (10, 0)>
def add(n1, n2):
print(n1 + n2)
def sub(n1, n2):
print(n1 - n2)
def mul(n1, n2):
print(n1 * n2)
def div(n1, n2):
print(n1 / n2)
firstNumber = int(input("first Number: "))
secondNumber = int(input("second Number: "))
add(firstNumber, secondNumber)
sub(firstNumber, secondNumber)
mul(firstNumber, secondNumber)
div(firstNumber, secondNumber)
<예외발생 유형 2>
print(10 / 0)
<예외발생 유형 3>
print(int("hello"))
<예외발생 유형 4>
lists = [1, 2, 3, 4, 5, 6]
print(lists[6])
29
<try~except>
n1 = 10; n2 = 0
try:
print(n1 / n2)
except:
print("예상치 못한 예외가 발생했습니다.")
print("다음 프로그램이 정상 실행됩니다.")
print(n1 * n2)
print(n1 - n2)
print(n1 + n2)
<실습>
nums = []
n = 1
while n < 6:
try:
num = int(input("input number: "))
except:
print("예외 발생!!")
continue
nums.append(num)
n += 1
print(f"nums: {nums}")
30
<~else>
nums = []
n = 1
while n < 6:
try:
num = int(input("input number: "))
except:
print("예외 발생!!")
continue
else:
if num % 2 == 0:
nums.append(num)
n += 1
else:
print("입력한 숫자는 홀수입니다.", end="")
print("다시 입력 하세요")
continue
print(f"nums: {nums}")
<실습>
eveList = []; oddList = []; floatList = []
n = 1
while n < 6:
try:
num = float(input("input number: "))
except:
print("exception raise!!")
print("input number again!!")
continue
else:
if num - int(num) != 0:
print("float number!")
floatList.append(num)
else:
if num % 2 == 0:
print("even number!!")
eveList.append(int(num))
else:
print("odd number!!")
oddList.append(int(num))
n += 1
print(f"eveList: {eveList}")
print(f"oddList: {oddList}")
print(f"floatList: {floatList}")
31
<finally>
try:
inputData = input("input number: ")
numInt = int(inputData)
except:
print("exception raise!!")
print("not number!!")
numInt = 0
else:
if numInt % 2 == 0:
print("inputData is even number!!")
else:
print("inputData is odd number!!")
finally:
print(f"inputData: {inputData}")
<실습>
evenList = []; oddList = []; floatList = []; dataList = []
n = 1
while n < 6:
try:
data = input("input number: ")
floatNumber = float(data)
except:
print("exception raise!!")
print("not number!!")
continue
else:
if floatNumber - int(floatNumber) != 0:
print("float Number!!")
floatList.append(floatNumber)
else:
if floatNumber % 2 == 0:
print("even Number!!")
evenList.append(int(floatNumber))
else:
print("odd Number!!")
oddList.append(int(floatNumber))
n += 1
finally:
dataList.append(data)
print(f"evenList: {evenList}")
print(f"oddList: {oddList}")
print(f"floatList: {floatList}")
print(f"dataList: {dataList}")
32
<Exception>
num1 = int(input("input number: "))
num2 = int(input("input number: "))
try:
print(f"num1 / num2 = {num1 / num2}")
except Exception as e:
print(f"exception: {e}") # exception: division by zero
print(f"num1 * num2 = {num1 * num2}")
print(f"num1 - num2 = {num1 - num2}")
print(f"num1 + num2 = {num1 + num2}")
<raise>
def divCalculator(n1, n2):
if n2 != 0:
print(f"{n1} / {n2} = {n1 / n2}")
else:
raise Exception("0으로 나눌 수 없습니다.")
num1 = int(input("input number: "))
num2 = int(input("input number: "))
try:
divCalculator(num1, num2)
except Exception as e:
print(f"Exception: {e}")
<실습>
def sendSMS(msg):
if len(msg) > 10:
raise Exception("길이 초과!! MMS전환 후 발송!!", 1)
else:
print("SMS 발송!!")
def sendMMS(msg):
if len(msg) <= 10:
raise Exception("길이 미달!! SMS전환 후 발송!!", 2)
else:
print("MMS 발송!!")
msg = input("input message: ")
1) --------------------------------
try:
sendSMS(msg)
except Exception as e:
print(f"e: {e.args[0]}")
print(f"e: {e.args[1]}")
if e.args[1] == 1:
sendMMS(msg)
elif e.args[1] == 2:
sendSMS(msg)
2) -------------------------------
try:
sendMMS(msg)
except Exception as e:
print(f"e: {e.args[0]}")
print(f"e: {e.args[1]}")
if e.args[1] == 1:
sendMMS(msg)
elif e.args[1] == 2:
sendSMS(msg)
33
<사용자 예외 클래스>
class NotUseZeroException(Exception):
def __init__(self, n):
super().__init__(f"{n}은 사용할 수 없습니다!!")
def divCalculator(n1, n2):
if n2 == 0:
raise NotUseZeroException(n2)
else:
print(f"{n1} / {n2} = {n1 / n2}")
num1 = int(input("input number: "))
num2 = int(input("input number: "))
try:
divCalculator(num1, num2)
except NotUseZeroException as e:
print(e)
<실습>
class PasswordLengthShortException(Exception):
def __init__(self, str):
super().__init__(f"{str}: 길이 5미만!!")
class PasswordLengthLongException(Exception):
def __init__(self, str):
super().__init__(f"{str}: 길이 10초과!!")
class PasswordWrongException(Exception):
def __init__(self, str):
super().__init__(f"{str}: 잘못된 비밀번호!!")
adminPW = input("input admin password: ")
try:
if len(adminPW) < 5:
raise PasswordLengthShortException(adminPW)
elif len(adminPW) > 10:
raise PasswordLengthLongException(adminPW)
elif adminPW != "admin1234":
raise PasswordWrongException(adminPW)
elif adminPW == "admin1234":
print("빙고!")
except PasswordLengthShortException as e1:
print(e1)
except PasswordLengthLongException as e2:
print(e2)
except PasswordWrongException as e3:
print(e3)
자료출처: 제로베이스 데이터 스쿨