[28-32] 파이썬 중급(예외)

이재은·2024년 5월 14일

28강.

1. 예외란?

1) 문법적 문제는 없으나 실행 중 발생하는 예상치 못한 문제
에러는 소프트웨어 적으로 해결 불가(ex. 네트워크 연결)한 것을 말함
전체 실행에 영향이 없도록 처리해주어야함.

2) Exception 클래스를 상속함
Exception - SyntaxError - IndendtationError

29강.

2. 예외처리

1) try ~ except

  • '예외 발생 예상 구문'을 try ~ except로 감쌈
  • 예외 발생시 except부터 실행
  • 예외 미발생시 try ~ except에서 벗어나 나머지 실행
n1 = 10 ; n2 = 0
try :
    print(n1 / n2)

except :
    print('예상치 못한 문제가 발생했습니다.!')
    print('다음 프로그램이 정상 실행됩니다.')

print(n1 * n2)
print(n1 - n2)
print(n1 + n2)코드를 입력하세요

30강.

2) try ~ except ~ else :

  • else : 예외가 발생하지 않은 경우 실행하는 구문

31강.

3) finally : 예외발생과 상관없이 항상 실행

32강.

3. Exception class

1) Exception as e : 어떤 예외가 발생했는지 정보를 얻을 때 사용

num1 = int(input())
num2 = int(input())

try :
    print (num1 / num2)
except Exception as e : #맨 나중에 써주기
    print('0으로 나눌 수 없습니다')
    print(f'exception : {e}')

print(num1 * num2)
print(num1 - num2)
print(num1 + num2)코드를 입력하세요

2) raise Exception('~~') : 예외 발생시키기

def divCal (n1, n2):

    if n2 != 0 :
        print(n1 / n2)
    else :
        raise Exception ('0으로 나눌 수 없습니다') #이게 밑으로 들어감

num1 = int(input('input number 1 '))
num2 = int(input('input number 2 '))

try :
    divCal(num1, num2)
except Exception as e :
    print(f'{e}')
   
  • 실습 ★
msg = input()
    
def sendSMS(msg):
    if len(msg) > 10 :
        raise Exception('길이 초과', 1)
    else :
        print('sms 발송 !!')

def sendMMS(msg):
    if len(msg) <= 10 :
        raise Exception('길이 미달! sms 전환 후 발송', 2)
    else :
        print('MMS 발송 !!')
------------
msg = input('input message : ')

try :
    sendSMS(msg)

except Exception as e :
    print({e.args[0]}) #exception 매개변수 두개를 만들수 있음
    print({e.args[1]})

    if e.args[1] == 1 :
        sendMMS(msg)
    elif e.args[1] == 2 :
        sendSMS(msg)

33강.

4. 사용자 예외 클래스 ★

#1
class NotUseZeroException(Exception): #요렇게 상속
	#2 
    def __init__(self, n):
        super().__init__(f'{n}은 사용할 수 없습니다')

def divCalculator(n1, n2):

    if n2 == 0:   #3 여기서 n2가 위로 올라감
        raise NotUseZeroException(n2)
    else :
        print(f'{n1} / {n2} = {n1/ n2}')

------------------------

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

try :
    divCalculator(num1, num2)
except NotUseZeroException as e :
    print(e)
  • 실습 ★
class PasswordShortEx(Exception) :
    
    def __init__(self, str):
        super().__init__(f'{str}: 길이 5미만!')
class PasswordlongEx(Exception) :
    def __init__(self, str):                        
        super().__init__(f'{str}: 길이 10 초과!')     
        
class PasswordWrongEx(Exception) :
    def __init__(self, str):
        super().__init__(f'{str}: 잘못된 비밀번호')     
        
adminPw = input()

try :
    if len(adminPw) < 5 : 
        raise PasswordShortEx(adminPw)
    if len(adminPw) > 10 :
        raise PasswordlongEx(adminPw)
    elif adminPw != 'admin1234':
        raise PasswordWrongEx(adminPw)
    elif adminPw == 'admin1234' :
        print('빙고')
    
    
except PasswordShortEx as e1 :
    print(e1)
    
except PasswordlongEx as e2 :
    print(e2)
    
except PasswordWrongEx as e3 :
    print(e3)
profile
Dare to be an optimist

0개의 댓글