Python 주요Error 정리
파이썬에서 발생하는 에러의 종류는 굉장히 다양하다. 미리 에러의 종류들을 이해하고 에러가 났을 때 당황하지 않고 어떤 부분이 잘못 되었는가 확인하고 수정하면 된다! 그래서 자주 나오는 에러들만 정리 해보고자 한다.
1. SyntaxError : 문법이 잘못됨. (괄호, 따옴표)
error msg) Syntax Error : invalid syntax
if x = y:
# SyntaxError: invalid syntax
# 수정) if x == y:
2. NameError : 참조변수 없음. 선언이 안됨.
error msg) name '예시' is not defined
emilia = 10
print(emillia)
# NameError: name 'emillia' is not defined
3. ZeroDivisionError : 0으로 나누기 에러. 0으로 나누기 불가.
error msg) ZeroDivisionError : division by zero
a = 10
b = 0
print(a/b)
# ZeroDivisionError : division by zero
4. IndexError : 인덱스 범위 넘어섬.
error msg) IndexError: list index out of range
x = [0,1,2,3,4]
print(x[10])
# IndexError: list index out of range
5. KeyError : Dictionary 에서 Key값을 찾을 수 없음
error msg) KeyError : '(예시)'
dic = {'name' : 'emilia', 'age' : '20 + alpha'}
print(dic['weight']) #key쓸 때는 중괄호
# KeyError: 'weight'
# KeyError 발생하지 않으려면 get 메서드 사용
dic = {'name' : 'emilia', 'age' : '20 + alpha'}
print(dic.get('weight')) #get메서드 사용시 소괄호
# None
6. AttributeError : 모듈 클래스에 있는 잘못된 속성 사용시 발생하는 예외
error msg) AttributeError : module '(예시)' has no attribute '(예시)'
import random
a = random.rand(0,10)
print(a)
# AttributeError: module 'random' has no attribute 'rand'
7. ValueError : 참조값이 없을 때 발생.
error msg) ValueError : (예시) is not in list
x = ['kim', 'park', 'lee', 'choi']
print(x.index('jung'))
# ValueError : 'jung' is not in list
8. FilenotFoundError : 외부파일을 찾지 못 함. 정확한 파일경로와 파일명 입력 필요.
error msg) FileNotFoundError : [Errno2] No such file or directory: '파일명'
f = open('안녕하세요.txt','r')
# FileNotFoundError : [Errno 2] No such file or dicrectory: '안녕하세요.txt'
9. TypeError : 데이터 타입으로 인한 오류.
error msg) TypeError : can only concatenate list (not "tuple") to list
x = [3]
y = (1.5)
z = 'text'
print(a+b+c)
#TypeError : can only concatenate list (not "tuple") to list
10. IndentationError : 들여쓰기 오류
error msg) IndentationError : unindent does not match any outer indentation level
x = [3]
y = (1.5)
z = 'text'
# IndentationError: unexpected indent
11. OverflowError : 연산 결과가 너무 커서 타입 표현이 불가
error msg) OverflowError: integer division result too large for a float
a = 2 ** 123456
b = 5
print(a/b)
#OverflowError : integer division result too large for a float
+)
AssertionError : assert 문이 제대로 작동하지 않을때 발생
MemoryError : 메모리가 부족하지만, 가비지 컬렉터가 일부 객체의 삭제를 함으로써 복구될 수 있는 경우 발생
OSError : 시스템 함수가 시스템 관련 에러를 돌려줄 때 발생
RecursionError : 최대 재귀 깊이가 초과하였을때 발생
파이썬의 대부분의 에러는 Exception 클래스에 의해 파생이 된다. Exception 클래스가 맨 위에 있고 그 아래에 IndexError, ValueError 등이 있는 것이다. 이것들 외에도 많은 Error 가 있으니 https://docs.python.org/ko/3/library/exceptions.html 참고!!
이런 에러들을 유도리있게 넘어가도록 하기 위해선 예외처리(try exception)가 필요하다. 그 내용은 다음 장에서 정리해야겠다!