Python 중급 5. 예외

yoong·2023년 4월 17일

1. Python

목록 보기
14/21

Python 중급 5.

01.예외

: 문법적인 문제는 없으나 실행 중 예상하지 못한 문제로 프로그램 실행이 어려운 상태

1. 예외처리

: 예상 하지 못한 예외가 프로그램 전체 실행에 영향이 없도록 처리하는 것,

방법 1. try ~except

[실습]

nums = []

n = 1
while n < 6:

    try:
        num = int(input('input number:'))
    except:
        print('잘못 입력하셨습니다 숫자를 입력해주세요!!')
        continue
    nums.append(num)
    n += 1

print(f'nums: {nums}')

방법 2. try~ excpet~else

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}')

방법 3. finally

:예외 발생여부와 상관없이 항상 실행하기
ex)외부 자원을 가지고 작업을 할 때, '자원 해제'단계에 사용함..?

try:
    inputData = input('input number: ')
    numInt = int(inputData)
except:
    print('exception raise!!')
    print('not number!!')
else:
    if numInt % 2 == 0:
        print('even numbmer!! ')
    else:
        print('odd number')
finally:
    print(f'inputData: {inputData}')

[실습]

oddList = []; evenList= []; floatList = []
dataList = []

n = 1
while n < 6:

    try:
        data = input('input number: ')
        floatNum = float(data)
    except:
        print('exception raised!')
        print('not number')
        continue

    else:
        if floatNum - int(floatNum) != 0:
            print('float Number')
            floatList.append(floatNum)

        else:
            if floatNum % 2 == 0:
                print('even Number')
                evenList.append(int(floatNum))
            else:
                print('odd Number')
                oddList.append(int(floatNum))


            n += 1

    finally:
        dataList.append(data)

print(f'evenList: {evenList}')
print(f'oddList: {oddList}')
print(f'floatList: {floatList}')
print(f'dataList: {dataList}')

2. Exception

:예외를 담당하는 클래스 ( 왜 예외가 일어낫는지 알수있음)

num1 = int(input('input number1: '))
num2 = int(input('input number2:  '))

try:
    print(f'num1 / num2 = {num1 / num2} ')
except Exception as e:
    print('0으로 나눌 수 없습니다.')
    print(f'exception: {e}')


print(f'num1 + num2 = {num1 + num2 }')
print(f'num1 - num2 = {num1 - num2 }')

3. raise

:예외를 발생시킬 수 있음.

def divCalculator(n1,n2):

    if n2 != 0:
        print(f'{n1}/{n2} = {n1 / n2}')
    else:
        raise Exception('0으로 나눌 수 없음')

num1 =int(input('input number1: '))
num2 =int(input('input number2: '))

try:
    divCalculator(num1, num2)
except Exception as e:
    print(f'Exception: {e}')

[실습]



def sendSMS(msg):

    if len(msg) > 10:
        raise Exception('10글자 초과: MMS 전환 후 발송',1)

    else:
        print('SMS 발송')

def sendMMS(msg):

    if len(msg) <= 10:
        raise Exception('10글자 이하: SMS 전환 후 발송',2)
    else:
        print('MMS 발송!')

msg = input('문자를 입력하세요: ')

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)

4. 사용자 Exception 클래스

:Exception 클래스를 상속해서 사용자 예외 클래스를 만들 수 있음.

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 number1: '))
num2 = int(input('input number1: '))

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)

Reference

  • 이글은 제로베이스 데이터 취업 스쿨의 강의자료 일부를 발췌하여 작성되었음.
profile
데이터와 이미지로 세상을 공부하는 중입니다 :)

0개의 댓글