Python Tutorial: Using Try/Except Blocks for Error Handling
오류 예외 처리 기법 (try, except를 활용해서)

이렇게 파일 불러오는 오류가 있다고 가정했을때, 이 오류를 다 보여주지 않고 내가 원하는 커스텀문장이 나오도록 try except를 활용해서 만들 수 있다.
try:
f=open('Newfile.txt')
except Exception:
print('Sorry, This file does not exist.')
#Sorry, This file does not exist 출력
try :
오류가 발생할 수 있는 구문
except Exception:
print('원하는 문장')
위에서 Exception은 굉장히 general 해서 모든 오류를 다 포괄한다. (IndexError, DivisionZero Error 등..)
만약 여러 오류 중 하나만 잡고 싶을 때는 특정 오류만 except에 따로 지정해준다.
이제는 파일 여는건 오류 없고 vars=notvars 라는 오류만 있을 때
try:
f=open('Newfile.txt')
vars = notvars
except FileNotFoundError: -> FileNotFoundError 한정
print('Sorry, This file does not exist.') -> 이거는 해당되지 않아서 넘어간다
except Exception:
print('Sorry, Something went wrong.')
#Sorry, Something went wrong. 출력
오류 메세지 변수를 e로 지정하고 e를 출력하는 방식을 사용할 수 있다.
except Exception as e:
print(e)
try:
f=open('Newfile.txt')
vars = notvars
except FileNotFoundError as e:
print(e)
except Exception as e:
print(e)
#name 'notvars' is not defined 출력
오류가 없을때 실행시키고 싶은 것은 else를 사용한다.
finally는 try 문 수행 도중 예외 발생 여부에 상관 없이 항상 수행되고, 보통 사용한 리소스를 close할 때 사용한다.
try :
오류가 발생할 수 있는 구문
except Exception as e:
print(e)
else:
오류가 발생하지 않았을 때 실행 할 것
finally:
무조건 마지막에 실행시키는 것 (오류가 있든 없든)
오류 회피하기
pass를 사용하면 오류가 발생하지 않고 그냥 통과된다.
try:
vars = notvars
except Exception as e:
print(e)
#name 'notvars' is not defined 출력
^ 기존 오류
try:
vars = notvars
except Exception:
pass
#아무것도 출력되지 않는다.
^ 오류 회피로 pass를 하면 아무것도 출력되지 않는다.
오류 일부러 발생시키기
raise 명령어 사용
class Bird:
def fly(self):
raise NotImplementedError
class Eagle(Bird):
pass
eagle = Eagle()
eagle.fly()
Bird라는 클래스를 상속받는 자식 클래스는 반드시 fly 함수를 구현해야 한다 : raise NotImplementedError의 의미
NotImplementedError는 꼭 작성해야 하는 부분이 구현되지 않았을 경우, 일부러 오류를 일으키기 위해 사용된다.
class Bird:
def fly(self):
raise NotImplementedError
class Eagle(Bird):
def fly(self): -> fly함수를 반드시 구현해야 오류나지 않는다.
print("Very fast")
eagle = Eagle()
eagle.fly()
#Very fast 출력
'Python' 카테고리의 다른 글
[TIL] 220804 파이썬 csv 파일 행 단위 읽기, 행 넘기기 next() (0) | 2022.08.04 |
---|---|
[TIL] 220731 While 과 For 사용 (0) | 2022.07.31 |
[점프 투 파이썬] 생성자(Constructor)와 클래스의 상속, 메서드 오버라이딩(Method Overriding), 클래스 변수 (0) | 2022.07.31 |
[점프 투 파이썬] 클래스 (0) | 2022.07.31 |
[점프 투 파이썬] 파일 읽고 쓰기 (0) | 2022.07.31 |