CHAPTER 14 예외

유동헌·2021년 9월 23일
0

열혈파이썬_기초편

목록 보기
14/14

01 예외가 발생하는 상황

먼저 몇 가지 오류 상황을 만들어보겠다.

lst = [1,2,3]
print(lst[3])

Traceback (most recent call last):
  File "/Users/dongheon/Desktop/development/python study/practice/practice.py", line 90, in <module>
    print(lst[3])
IndexError: list index out of range

print(3 + "coffee")

Traceback (most recent call last):
  File "/Users/dongheon/Desktop/development/python study/practice/practice.py", line 89, in <module>
    print(3 + "coffee")
TypeError: unsupported operand type(s) for +: 'int' and 'str'

print(3/0)

Traceback (most recent call last):
  File "/Users/dongheon/Desktop/development/python study/practice/practice.py", line 89, in <module>
    print(3/0)
ZeroDivisionError: division by zero
  • IndexError
  • TypeError
  • ZeroDivisionError

02 예외의 처리

프로그램 실행 중간에 예외가 발생하면 프로그램은 그냥 종료가 된다. 문제가 발생했으므로 계속 실행을 이어가는 것이 의미가 없거나 더 큰 문제로 이어질 수 있기 때문에 그냥 종료하는 것이 낫다고 파이썬은 판단하는 것이다. 이와 관련해서 다음 예를 보자. 이는 프로그램 사용자로부터 나이를 입력받는 매우 간단한 예제이다.

def main():
    print("안녕하세요")
    age = int(input("나이를 입력하세요 : "))
    print("나이 : ", age)
    print("만나서 반가웠습니다.")
    
main()

Traceback (most recent call last):
  File "/Users/dongheon/Desktop/development/python study/practice/practice.py", line 95, in <module>
    main()
  File "/Users/dongheon/Desktop/development/python study/practice/practice.py", line 91, in main
    age = int(input("나이를 입력하세요 : "))
ValueError: invalid literal for int() with base 10: '스물'

그런데 위 예제에는 한 가지 아쉬운 점이 있다. 그것은 오류 발생 시 만나서 반가웠습니다, 라는 인사를 하지 않는다는 점이다. 사실 다음 문장은 오류 발생 유무에 상관없이 실행되면 좋은 문장 아닌가!

def main():
    
    print("안녕하세요")
    
    try:
        age = int(input("나이를 입력하세요 : "))
        print("나이 : ", age)
        
    except ValueError:
        print("입력이 잘못 되었습니다")
        
    print("만나서 반가웠습니다")
    
main()

# 출력
안녕하세요
나이를 입력하세요 : 스물 
입력이 잘못 되었습니다
만나서 반가웠습니다

위의 코드는 다음 그림에서 try 영역과 except 영역으로 나뉜다.

그리고 try 영역에 있는 문장들이 실행되다가 예외가 발생하면, 그 순간 바로 except 영역으로 실행 흐름이 넘어가서 except 영역에 있는 문장들이 실행된다.

except 영역이 실행이 되고 나면, 해당 예외는 처리된 것으로 판단하고 except 영역 그 다음 문장부터 실행을 이어간다.

그런데 위의 except 선언을 보면 ValueError라고 쓰여 있는데 이는 ValueError 예외만 처리한다는 뜻이다. 따라서 try 영역에서 ValueError 이외의 예외가 발생하면 그때는 이를 처리할 수 있는 except 영역이 없으므로 그냥 종료가 된다.

03 보다 적극적인 예외의 처리

입력이 잘못되었으면 재입력의 기회를 줘야 적절한 예외처리가 아니겠는가?

def main():
    
    print("안녕하세요")
    
    while True:
        
        try:
            age = int(input("나이를 입력해주세요 : "))
            print("입력한 나이 : ", age)
            break
        
        except ValueError:
            print("입력이 잘못 되었습니다")
            
    print("만나서 반가웠습니다")
    
main()

위의 예에서는 while 루프 안에 try, except를 넣어서 except 영역이 실행되면 while 루프를 반복하도록 하였다. 때문에 정상적인 입력이 없으면 프로그램 사용자에게 입력을 계속 요구하게 된다.

04 둘 이상의 예외를 처리하기

다음 예제에서 보이듯이 한 영역에서 발생 가능한 예외가 둘 이상인 경우도 있다.

def main():
    
    bread = 10
    
    people = int(input("몇 명? : "))
    print("1인당 빵의 수 :", bread/people)
    print("맛있게 드세요")
    
main()

# ValueError 발생 가능성
# ZeroDivisionError 발생 가능성

수정한 코드

def main():
    
    bread = 10
    
    try:
        people = int(input("몇 명 ? : "))
        print("1인당 빵의 수 : ", bread/people)
        print("맛있게 드세요")  
    
    except ValueError:
        print("입력이 잘 못 되었습니다")
    
    except ZeroDivisionError:
        print("0으로 나눌 수 없습니다")
    
main()

05 예외 메세지 출력하기와 finally

  • msg
def main():
    
    bread = 10
    
    try:
        people = int(input("몇 명 ? : "))
        print("1인당 빵의 수 : ", bread/people)
        print("맛있게 드세요")  
    
    except ValueError as msg:
        print("입력이 잘 못 되었습니다")
        print(msg)
    
    except ZeroDivisionError as msg:
        print("0으로 나눌 수 없습니다")
        print(msg)
main()
  • finally
def main():
    
    bread = 10
    
    try:
        people = int(input("몇 명 ? : "))
        print("1인당 빵의 수 : ", bread/people)
        print("맛있게 드세요")  
    
    except ValueError as msg:
        print("입력이 잘 못 되었습니다")
        print(msg)
    
    except ZeroDivisionError as msg:
        print("0으로 나눌 수 없습니다")
        print(msg)
        
    finally:
        print("프로그램 종료")
main()

06 모든 예외 그냥 무시하기

def main():
    
    bread = 10
    
    try:
        people = int(input("몇 명 ? : "))
        print("1인당 빵의 수 : ", bread/people)
        print("맛있게 드세요")
        
    except:
        print("뭔지는 몰라도 예외가 발생했다")

main()
profile
지뢰찾기 개발자

0개의 댓글