[Zero-Base]데이터 취업 스쿨 스터디 노트(5)

강현정·2024년 4월 13일

zero_base

목록 보기
6/54

✏️예외처리

try~except
예외 발생 예상 구문을 try~except로 감싼다.

n1 = 10;n2 = 0
try:
  print(n1/n2)
except:
  print('예상치 못한 문제가 발생했습니다.')
print(n1+n2)
print(n1*n2)
예상치 못한 문제가 발생했습니다.
10
0

이때 except에 pass를 적어주면 pass하고 다음 값들을 출력해준다.

#실습
nums = []

n = 1
while n<6:
  try:
    num = int(input('input number: '))
  except:
    print('예외발생')  
    continue

  nums.append(num)
  n+=1

print(nums)

✏️try~except~else

이때 else는 try~except를 작성하지 않을 경우 에러가 난다.

#실습
evenlist = [];oddlist = [];floatlist = []

n=1
while n < 6:

  try:
    num = float(input('input number:'))

  except:
    print('exception error')
    continue  

  else:
    if num - int(num) != 0:
      print('floatlist!!')
      floatlist.append(num)
    else:
      if num %2 ==0:
        print('evenlist!!')
        evenlist.append(num)
      else:
        print('oddnumber!!')
        oddlist.append(num)
        

✏️finally

❓사용이유
네트워크와 연결된 외부자원을 사용하는 도중에 예외가 발생하든 안 하든 그 작업을 꼭 실행을 해야할 경우 finally에서 사용한다.

evenlist = [];oddlist = [];floatlist = [];datalist = []

n=1
while n < 6:

  try:
    data = input('input number:') #처음부터 float로 묶어주면 string형식이 들어올경우 
    #[1.0, 1.0, 1.0, 1.0, 2.0, 3.0, 4.0, 5.0]처럼 숫자로 인식하므로 구분해주어야 한다.
    floatNum = float(data) 

  except:
    print('exception error')
    continue  

  else:
    if floatNum- int(floatNum) != 0:
      print('floatlist!!')
      floatlist.append(floatNum)
    else:
      if floatNum %2 ==0:
        print('evenlist!!')
        evenlist.append(int(floatNum))
      else:
        print('oddnumber!!')
        oddlist.append(int(floatNum))
        
    n+=1

  finally: 
    datalist.append(data)

print(datalist)

🌟Summary
try~except~else~finally를 통해 예외 구문을 효율적으로 관리할 수 있다.

✏️Exception 클래스

exception클래스
exception클래스를 통해 예외를 관리할 수 있으며 raise키워드를 이용하여 예외를 발생시킬 수 있다. 아래의 실습내용과 같이 raise를 함수 내부에 작성하여 조건에 맞게 예외 상황을 처리할수 있다. #2의 경우 여러개의 예외 클래스를 만들 경우 except도 여러개를 사용해서 예외처리를 해주면 된다.

#1
def sendSMS(msg):

    if len(msg)>10:
        raise Exception('길이 초과!! MSS전환 후 발송!!',1)
    else:
        print('SMS발송')

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

msg = input('input msg: ')

try:
    sendSMS(msg)

except Exception as e:
    print(e.args[0])
    print(e.args[1])

    if e.args[1] ==1:
        sendMMS(msg)
    if e.args[1] ==2:
        sendSMS(msg)
#2
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)
    else:
        print('빙고!!')
    
except PasswordLengthShortException as e1:
    print(e1)
except PasswordLengthLongException as e2:
    print(e2)
except PasswordWrongException as e3:
    print(e3)

0개의 댓글