티스토리 뷰

예외 처리

예외(exception)
런타임 에러

에러처리 방법

추가코딩
예외 상황에 대비하여 미리 처리한다
예상치 못했던 문제가 발생했을 때 처리할 수 없다.
먼저 실행하고, 나중에 복구하기

에러가 생기도록 나둔 다음에 에러가 생기면 처리한다.

코드가 해야 할 일에 집중한다.

import os

try :
    data = open('sketch.txt')

    for each_line in data :
        try :
            (role, line_spoken) = each_line.split(':', 1)
            print(role, end='')
            print(' said ', end='')
            print(line_spoken, end='')
        except ValueError:
            pass  

    data.close()

except IOError:
    print('The data file is missing!')
    

try/exception

try :
    //런타임 에러를 발생시킬 수도 있는 코드
exception :
    //정의된 에러 복구 코드

함수, 키워드 등

  • not : 조건을 반대로 만든다.
  • pass : 빈(empty, null) 문장으로 아무런 처리도 하지 않는다.

split(...) 도움말

>>> help(each_line.split)
Help on built-in function split:

split(...) method of builtins.str instance
    S.split(sep=None, maxsplit=-1) -> list of strings
    
    Return a list of the words in S, using sep as the
    delimiter string.  If maxsplit is given, at most maxsplit
    splits are done. If sep is not specified or is None, any
    whitespace string is a separator and empty strings are
    removed from the result.

터플(tuple)

변할 수 없는 리스트;불변형 리스트)

예 : (role, line_spoken)부분

댓글