에러와 예외
에러(Error)는 프로그램 실행 중 발생하는 문제를 일반적으로 지칭. 컴파일 타임 에러(문법 에러 등)와 런타임 에러(실행 중 발생하는 에러)를 모두 포함할 수 있음.
예외(Exception)는 런타임 에러 중 하나로, 프로그램의 정상적인 흐름을 방해하는 이벤트. 예외는 예상 가능하고 프로그램에서 처리할 수 있는 에러를 의미. 예외처리 로직을 통해 프로그램이 비정상적으로 종료되지 않고 예외상황을 처리하거나 회복할 수 있음.
# 기본구조
try:
# 예외가 발생할 수 있는 코드
# 예외가 발생하면 이후 부분을 건너뛰고 except블록으로 이동함.
except:
# try블록에서 예외가 발생했을때 실행되는 코드
else:
# try블록에서 어떤 예외도 발생하지 않았을때 실행되는 코드
# try블록이 성공적으로 실행되면 이어서 else블록이 실행됨.
finally:
# 예외의 발생여부와 관계없이 실행되는 코드
# 필수적인 정리작업용. ex) 열린파일을 닫거나, 네트워크연결 종료 등
try를 통해 코드의 오류를 테스트할 수 있다. 만약 예외가 일어나면 예외가 일어난 코드 이후의 코드는 스킵되고 except에 있는 코드를 실행한다.
except을 사용하면 오류를 처리할 수 있다. 만약 예외가 일어나지 않았다면 except은 스킵. 예외별로 구분하여 여러 except가 가능하다.
else를 사용하면 오류가 없을때 코드를 실행할 수 있다.
finally를 사용하면 결과에 관계없이 코드를 실행할 수 있다. finally는 선택이지만, 한 try구문에는 하나의 finally만 사용가능.
예외 객체 사용
try:
# 예외가 발생할 수 있는 코드
except Exception as e:
print(f"오류 발생: {e}")
traceback 모듈
오류가 발생했을때, 그 오류의 추적정보(traceback)를 얻기 위해 traceback 모듈 사용
import traceback
try:
# 예외가 발생할 수 있는 코드
except Exception as e:
traceback.print_exc() # 현애 예외의 traceback 정보를 콘솔에 직접 출력
trace_str = traceback.format_exc() # 현재 예외의 traceback 정보를 문자열로 반환
print(trace_str)
logging 모듈
에러 로그를 파일이나 콘솔에 기록할 수 있으며, 예외정보를 포함시킬 수 있음. 현재발생한 예외에 대한 로그 메시지를 생성하면서 자동으로 예외 정보를 로그에 추가함.
import logging
try:
# 예외가 발생할 수 있는 코드
except Exception as e:
logging.exception("예외발생!")
raise
raise 키워드를 사용하면 직접 예외를 발생시킬 수 있음. 어떠한 종류의 에러를 발생시킬지 지정할 수 있음.
# 예시
raise Exception("예외 발생")
raise TypeError("Only integers are allowed")
| Exception | Cause of Error |
|---|---|
| AssertionError | Raised when an assert statement fails. |
| AttributeError | Raised when attribute assignment or reference fails. |
| EOFError | Raised when the input() function hits end-of-file condition. |
| FloatingPointError | Raised when a floating point operation fails. |
| GeneratorExit | Raise when a generator's close() method is called. |
| ImportError | Raised when the imported module is not found. |
| IndexError | Raised when the index of a sequence is out of range. |
| KeyError | Raised when a key is not found in a dictionary. |
| KeyboardInterrupt | Raised when the user hits the interrupt key (Ctrl+C or Delete). |
| MemoryError | Raised when an operation runs out of memory. |
| NameError | Raised when a variable is not found in local or global scope. |
| NotImplementedError | Raised by abstract methods. |
| OSError | Raised when system operation causes system related error. |
| OverflowError | Raised when the result of an arithmetic operation is too large to be represented. |
| ReferenceError | Raised when a weak reference proxy is used to access a garbage collected referent. |
| RuntimeError | Raised when an error does not fall under any other category. |
| StopIteration | Raised by next() function to indicate that there is no further item to be returned by iterator. |
| SyntaxError | Raised by parser when syntax error is encountered. |
| IndentationError | Raised when there is incorrect indentation. |
| TabError | Raised when indentation consists of inconsistent tabs and spaces. |
| SystemError | Raised when interpreter detects internal error. |
| SystemExit | Raised by sys.exit() function. |
| TypeError | Raised when a function or operation is applied to an object of incorrect type. |
| UnboundLocalError | Raised when a reference is made to a local variable in a function or method, but no value has been bound to that variable. |
| UnicodeError | Raised when a Unicode-related encoding or decoding error occurs. |
| UnicodeEncodeError | Raised when a Unicode-related error occurs during encoding. |
| UnicodeDecodeError | Raised when a Unicode-related error occurs during decoding. |
| UnicodeTranslateError | Raised when a Unicode-related error occurs during translating. |
| ValueError | Raised when a function gets an argument of correct type but improper value. |
| ZeroDivisionError | Raised when the second operand of division or modulo operation is zero. |