본문 바로가기

Python

[파일과 예외] try/except


[파일과 예외] try/except

코드가 잘못될 경우 파이썬 인터프리터가 다음과 같은 traceback이라는 메세지를 출력하는 것을 본 경우가 있을 것입니다.


역추적(traceback) : 발생한 런타임 에러에 대한 상세한 설명
예외는 런타임 에러에 의해 발생하며, 역추적하게 만듭니다.


예외 처리 메커니즘은 일단 에러가 발생하도록 놔두고, 에러가 발생하면 발견해서 복구할 수 있도록 합니다.
코드를 수행하다가 문제가 발생하면 예외적으로 실행되는 복구 코드가 작동하고, 계속 정상 처리할 수 있도록 합니다.

이때 try/except 메커니즘을 사용합니다.

>>>try:
          런타임 에러를 발생시킬 수도 있는 코드
     except:
          여러분이 정의한 에러 복구 코드

>>> data=open('hellow.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:
          pass  #만약 런타임 에러가 생기면 이 코드가 실행됩니다.
  
Man said: Is this the right room for an argument?
Other man said: I've told you once.
Man said: No you haven't!
Other Man said: Yes I have.
Man said: When?
Ohter Man said: Just now!
Man said: No, you didn't
Ohter Man said: Anyway, I did.
Man said: You most certainly did not!
Ohter Man said : Now let's get one thing quite clear : I most definitely told you!
Man said: oh no you didn't!
Ohter Man said: oh yes I did!
Man said: (exasperated) oh, this is futile!!
(pause)
Ohter Man said: No it isn't!
Man said: yes it is!

try문 안에 에러가 발생하는 코드가 있어서 except의 pass 가 실행되어 에러없이 코드가 작동되었습니다.