파이썬 프로그램 실행 중에 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)
'Python' 카테고리의 다른 글
[Python] heapq (min heap) (0) | 2021.06.27 |
---|---|
[Python] for문 사용해서 list 원소 값 변경하는 방법 (0) | 2021.06.23 |
[Python] set 자료형 remove() vs. discard() (0) | 2021.05.15 |
[부스트코스] [모두를 위한 파이썬] 변수, 표현식, 문장 (0) | 2021.05.14 |
[부스트코스] [모두를 위한 파이썬] 예약어, 순차문, 조건문 및 반복문 (0) | 2021.05.14 |