본문 바로가기
Python

[파이썬] 예외처리 예제 (try, except, else, finally, raise)

by 메이플 🍁 2022. 3. 23.

⚠️ 이 포스팅은 인프런님의 프로그래밍 시작하기 : 파이썬 입문 (Inflearn Original)을 공부하고 정리한 블로그 포스팅입니다. ⚠️

 

포스팅에 해당하는 목차는 다음과 같습니다:
섹션 7. 파이썬 예외처리

  • Exception(1-1)
  • Exception(1-2)

 


 

1. 예외처리 (exception)

1.1 예외란?

파이썬에서 에러메세지를 무시하고 싶을때 try, except 구문을 사용해서 오류를 예외적으로 처리하는것. 

 

1.2 예외 처리 기본 구조

try:
  ...
except:
  ...
  • try문이 실행되는 중에 오류가 발생하면 except문이 실행된다
  • try문이 실행되는 중에 오류가 발생하지 않으면 except문이 실행되지 않는다

 

예제1: try 구문 실행

try문이 실행되는 중에 오류가 발생하지 않으면 except문이 실행되지 않는다.

names = ['Emma', 'Isabella', 'Mia']

try:
  name = 'Emma'
  result = names.index(name)
  print('{} is in the list. Index Number: {}'.format(name, result))
except:
  print('Something went wrong')
# Emma is in the list. Index Number: 0

 

예제2: except 구문 실행

try문이 실행되는 중에 오류가 발생하면 except문이 실행된다.

names = ['Emma', 'Isabella', 'Mia']

try:
  name = 'Camila'
  result = names.index(name)
  print('{} is in the list. Index Number: {}'.format(name, result))
except:
  print('Something went wrong')
# Something went wrong

 

예제3: except 구문에 에러종류를 명시하고 실행하기

except 키워드 다음에 어떤 에러 종류인지 명시하면 상응하는 에러가 발생할때만 except구문이 실행된다. 에러 종류를 명시하지 않으면 종류에 상관없이 에러가 발생하면 except 구문이 실행된다.

names = ['Emma', 'Isabella', 'Mia']

try:
  name = 'Camila'
  result = names.index(name)
  print('{} is in the list. Index Number: {}'.format(name, result))
except ValueError:
  print('Something went wrong')
# Something went wrong

 

예제4: else

try문 수행중 오류가 발생하면 except 구문이 수행되고 오류가 없으면 try구문과 else 구문이 수행된다.
try:
  name = 'Emma'
  result = names.index(name)
  print('{} is in the list. Index Number: {}'.format(name, result))
except ValueError:
  print('Something went wrong')
else:
  print('else statement is executed when try code runs succesfully')
# Emma is in the list. Index Number: 0
# else statement is executed when try code runs succesfully

 

예제 5: finally

finally 구문은 예외처리에 실행여부에 관계 없이 마지막에 반드시 실행되어야 하는 구문이다. 

try:
  name = 'Emma'
  result = names.index(name)
  print('{} is in the list. Index Number: {}'.format(name, result))
except ValueError:
  print('Something went wrong')
else:
  print('else clause is executed when try clause runs succesfully')
finally:
  print('finally clause is always executed in the end')
# Emma is in the list. Index Number: 0
# else clause is executed when try clause runs succesfully
# finally clause is always executed in the end

댓글