[Py.7]

예외 처리

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

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


try ~ except ~ else 구문

  • 'try ~ except' 뒤에 오는 ~ else 구문은 예외가 발생하지 않은 경우 실행하는 구문이다
    .


finally 구문

  • 예외 발생과 상관없이 항상 실행함

실습 예시)

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

n = 1
while n < 6:

    try:
        data = input('input number: ')
        floatNum = float(data)

    except:
        print('exception raise!!')
        print('requesting new input!!')
        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}')

Exception 클래스

  • 예외 담당 클래스: 어떤 예외가 발생했는지 알려주는 것

실습 예제)

num1 = int(input('input number: '))
num2 = int(input('input number: '))

try:
    print(f'num1 / num2: {num1 / num2}')

except Exception as e:
# == except Exception as error
    print(f'exception: {e}')

print(f'num1 + num2: {num1 + num2}')
print(f'num1 - num2: {num1 - num2}')
print(f'num1 * num2: {num1 * num2}')
  • raise 키워드를 이용하여 예외 발생시킬 수 있음


[Py.8-9]

사용자 Exception 클래스

  • Exception 클래스를 상속하여 사용자 예외 클래스 만들 수 있다.

실습 예제)

# 사용자 Exception 클래스는 무조건 Exception을 상속 받아야 함
class NotUseZeroException(Exception):

    def __init__(self, n):
        super().__init__(f'{n}은 사용할 수 없습니다.')


def divCal(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:
    divCal(num1, num2)

except NotUseZeroException as e:
    print(e)

텍스트 파일 쓰기 & 읽기 & 열기

  • open(), read(), write(), close()를 이용한 텍스트 파일 다루기

1. 쓰기

  • write() 함수를 이용한 파일에 문자열 쓰기

2. 읽기

  • read() 함수를 이용한 파일 문자열 읽기

3. 열기

  • 파일 모드는 파일을 어떤 목적으로 open할 지 정한다.
    - 'w' : 쓰기 전용 (파일이 있으면 덮어씌움)
    - 'a' : 쓰기 전용 (파일이 있으면 덧붙임)
    - 'x' : 쓰기 전용 (파일이 있으면 에러 발생)
    - 'r' : 읽기 전용 (파일이 없으면 에러 발생)

with ~ as 문

  • with ~ as문을 이용하면 파일 닫기(close)를 생략할 수 있음


writelines()

  • 리스트(list) 또는 튜플 데이터를 파일에 쓰기 위한 함수


readlines() & readline()

  • readlines() 함수는 파일의 모든 데이터를 읽어서 리스트 형태로 반환한다.

  • readline() 함수는 한 행을 읽어서 문자열로 반환한다.

이상 데이터 취업 스쿨 Chp3 파이썬 중급의 저번 진도 이후의 스터디노트이다.

저번과 똑같이 진도를 따라잡는 중이며, 어려움은 사라지지 않는다.

빨리 진도를 따라잡아야 한다는 조급함이 남는다.





이미지 출처: @waterglasstoon, 제로베이스 강의 일부

profile
On My Way

0개의 댓글