본문 바로가기

Python

[부스트코스] [모두를 위한 파이썬] 예외처리(try, except)

파이썬 프로그램 실행 중에 Traceback이 발생하면 프로그램이 멈춘다. 이를 방지하기 위해서 try/except를 사용하자

try / except 구조

• 위험한 코드를 try/except 을 사용해 처리

• try 블록에 있는 코드가 성공하면 - except 블록을 건너뜀

• try 블록에 있는 코드가 실패하면 - except 블록을 실행

 

다음 코드를 실행하면

astr = 'Bob'
try:
    print('Hello')
    istr = int(astr)
    print('There')
except:
    istr = -1
print('Done', istr)

 

print('There')는 실행되지 않는다.

Hello
Done -1

Process finished with exit code 0

 

따라서 try/except는 보통 다음과 같이 한 줄만 사용하는 게 좋다.

astr = 'Bob'
print('Hello')
try:
    istr = int(astr)
except:
	istr = -1
print('There')
print('Done', istr)