PL/Python
[Python][짧은개념] 파이썬의 예외처리
SweetDev
2023. 1. 2. 15:20
try:
print(f"연산결과")
except:
print("에러 발생")
else:
print("정상 동작")
finally:
print("수행 종료")
Q) finally는 왜 쓰는걸까? 어차피 오류가 나던, 안나던 실행된다면 try문 바깥쪽에 적어도 되는거 아닌가?
A) try나 except에 return문이 있으면 함수 자체가 종료되어 버린다. finally문에서 함수가 끝날 때 처리해야 하는 액션들을 처리하고 리턴하도록 할 수 있다.
except에서 오류 종류로 판단하기
except ImportError:
# 대응하기
except ValueError:
# 대응하기
직접 오류 발생: raise로 오류 발생시키기
raise ValueError("입력값을 다시 확인하세요!")
Custom Exception
raise Exception("예외 발생!")
except로 처리해주면 된다.!
assert로 예외 발생시키기
assert는 지정된 조건식이 거짓일 때 AssertionError 예외를 발생시키며 조건식이 참이면 그냥 넘어갑니다. 보통 assert는 나와서는 안 되는 조건을 검사할 때 사용합니다.
assert는 디버깅 모드에서만 동작한다
assert x % 3 == 0, '3의 배수가 아닙니다.'
# class 예외명(Exception):
class FileExtensionError(Exception):
def __init__(self):
#super().__init__(예외 메세지)
super().__init__('파일 확장자를 확인해주세요.')
def read_csv(file):
try:
extension = file.split('.')[-1]
if extension != "csv":
raise FileExtensionError
csv = open(file, 'r')
return csv
except FileNotFoundError:
print("Can't Open {0}".format(file))
except Exception as e:
print("Error : {0}".format(e))
Exception의 동작 원리
- exception역시 하나의 instance이다. (Exception을 상속받은)
- exception발생시 stack을 하나하나 내려가면서 handler있는지 찾음 (python에서는 except문)
- main 함수까지 갔는데 없으면 프로그램은 죽어버린다.
c언어에서는 exception이라는 개념이 없었나???
—> ㅇㅇ없었음. c에서는 NULL이나 -1을 리턴함.