본문 바로가기
IT/Python

파이썬 기본 개요 - 오류, Exception

by 천빈 2021. 5. 6.

오류가 나올떄마다 머리가 아프다. 거기에 영어로 뜨는 오류는 보는순간 숨이 막힌다. 하지만 반대로 생각하면 이런 오류들을 해석해서 알아가는게 나의 코딩실력을 늘일 수 있는 기회가 되지 않을까 생각했다. 이러한 오류들을 알아보고자 한다.

 

>>> a = 'python"
  File "<stdin>", line 1
    a = 'python"
                ^
SyntaxError: EOL while scanning string literal

>>> a = python
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  
NameError: name 'hello' is not defined

>>> a = a + 1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
 
TypeError: can only concatenate str (not "int") to str

>>> a = int("abc")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  
ValueError: invalid literal for int() with base 10: 'abc'
SyntaxError: EOL while scanning string literal 문자열 literal을 읽던 도중 EOL(End of Line)을 만났다.
NameError: name 'python' is not defined  'python'의 이름이 정의되지 않았다.
TypeError: can only concatenate str (not "int") to str str에만 str을 연결할 수 있다(not int)
ValueError: invalid literal for int() with base 10: 'abc' int함수에 'abc'라는 적절하지 않은 값이 들어옴
semantic Error 프로그램 수행중에 발생할 수 있는 Error로 사전에 프로그래머가 처리할 수 있는 가벼운 에러
IndexError: list index out of range
자료형의 위치를 벗어남

 

 

Traceback

  • 예외는 실행 도중 발생하기 떄문에 'Traceback' 정보를 제공한다.
  • 이 call chain을 확인하면 어디에서 오류가 일어났는지 파악이 가능하다.
def except_test02():
    #try ~ else
    L = [1,2,3]
    try:
        num = L[5]
    except IndexError as IE:
        print("index error :", IE, type(IE))
        IE.with_traceback()
    else:
        print("keep calm and go ahead")
        
Traceback (most recent call last):
  File "C:\PythonWorkPJ\Day0506\com\test.py", line 15, in except_test02
    num = L[5]
IndexError: list index out of range

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\PythonWorkPJ\Day0506\com\test.py", line 28, in <module>
    except_test02()
  File "C:\PythonWorkPJ\Day0506\com\test.py", line 18, in except_test02
    IE.with_traceback()
TypeError: BaseException.with_traceback() takes exactly one argument (0 given)
===================
index error : list index out of range <class 'IndexError'>

Process finished with exit code 1

Traceback (most recent call last):

File "C:\PythonWorkPJ\Day0506\com\test", line 15, in except_test02
num = L[5]

IndexError: list index out of range

 :  이 문구를  보면 리스트의 INDEX가 범위를 벗어난 것을 알 수 있다.

 

 

Exception

  • 특정에러에 대응하는 방법을 클래스로 나타낸 것, pvm에서 특정에러에 대한 클래스를 제공한다.
  • 에러 중에서도 개발자가 프로그램 실행 시 중단의 경우를 대처할 수 있는 클래스이다.

ex) OA 프로그램에서 갑자기 병목현상이 발생할 경우, .bak 파일에 작업 내용을 자동 저장

ex) ZeroDivisionError: 예외 클래스

 

예외처리

  • 예외를 방치하거나 에러로 인한 프로그램 수행 결과가 잘못 동작하는 것이 아니라 에라를 잡고 처리하는 방법을 제공하는 것

 

Exception Handling : 예외가 발생한 곳에서 예외를 직접 처리한다.

try ~ except, try ~ else, try ~ finally, try ~ else ~ finally

 

try:

      <code block>

      예외 발생시 실행되는 코드

except 예외종류, 변수

       예외 발생시 실행되는 문구

else:

      예외가 발생되지 않았을 때 실행되는 코드

finally

      예외 발생 유무에 상관하지 않고 꼭 실행되는 코드

 

if __name__ == '__main__':
  
        r = 10/0

ZeroDivisionError: division by zero

 

r = 10/0을 실행시, 나오는 error

 

if __name__ == '__main__':
    try:
        r = 10/0
    except ZeroDivisionError:	# PVM에서 ERROR의 종류에 해당하는 클래스를 생성해서 리턴하는 것을 except에서 해결
        print("0으로 나눔")
       
0으로 나눔

try ~ except를 통해 예외처리한 모습

 

if __name__ == '__main__':
    try:
        r = 10/0
        print("11")
    except ZeroDivisionError:
        print("0으로 나눔")
   
0으로 나눔

try ~ 문은 실행이 중단되었기 때문에 11은 출력하지 않는다.

 

if __name__ == '__main__':
    try:
        r = 10/0
        print("11")
    except ZeroDivisionError:
        print("0으로 나눔")
    finally:					# 파일, db등의 close(), web logout 등
        print("222222")
       
0으로 나눔
222222

finally는 무조건 실행하기 때문에 출력된다. logout등의 기능 작성시 필요하다.

 

 

if __name__ == '__main__':
    try:
        r = 10/4
        print("11")
    except ZeroDivisionError:
        print("0으로 나눔")
    finally:
        print("222222")

11
222222

예외발생이 없기 때문에 print문이 정상적으로 출력

 

 

def except_test02():
    #try ~ else
    L = [1,2,3]
    try:
        num = L[5]
    except IndexError as IE:
        print("index error :", IE, type(IE))
    else:
        print("keep calm and go ahead")
     
index error : list index out of range <class 'IndexError'>

as로 별칭 설정 후, 불러오기로 에러의 내용을 알 수 있다.

 

 

def except_test02():
    #try ~ else
    L = [1,2,3]
    try:
        num = L[5]
    except IndexError as IE:
        print("index error :", IE, type(IE))
        IE.with_traceback()
    else:
        print("keep calm and go ahead")
        
Traceback (most recent call last):
  File "C:\PythonWorkPJ\Day0506\com\test.py", line 15, in except_test02
    num = L[5]
IndexError: list index out of range

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\PythonWorkPJ\Day0506\com\test.py", line 28, in <module>
    except_test02()
  File "C:\PythonWorkPJ\Day0506\com\test.py", line 18, in except_test02
    IE.with_traceback()
TypeError: BaseException.with_traceback() takes exactly one argument (0 given)
===================
index error : list index out of range <class 'IndexError'>

Process finished with exit code 1

with_traceback(): 예외객체를 돌려준다

 

 

 

사용자 Exception(예외 만들기)

class 예외이름(Exception):

class Myexception(Exception):
    def __init__(self, value):  # 4. value = err_msg -> value = Error
        self.value = value      # 5. 멤버변수 value = Error
    def __str__(self):
        return self.value

def raise_exception(err_msg):   # 2. err_msg = Error
    raise Myexception(err_msg)  # 3. err_msg

if __name__ == '__main__':
    try:
        raise_exception("Error")    # 1. 호출
    except Myexception as e:        # 6
        print(e)               # 7

raise: 사용자가 강제로 예외를 일으킬 때 사용하는 구문

try블록 안에서 함수를 호출하고 사용자 정의 에러 클래스로 예외를 처리하는 데모

 

 

import sys

if __name__ == '__main__':
    try:
        10/0
    except ZeroDivisionError as z:
        print(sys.exc_info())
        print(format(type(z)))
        print(format(z.args))
        print(format(z))
        
(<class 'ZeroDivisionError'>, ZeroDivisionError('division by zero'), <traceback object at 0x000002469EF28D40>)
<class 'ZeroDivisionError'>
('division by zero',)
division by zero

 exc_info() : 현재 발생한 예외정보를 튜플로 반환한다.