Handling Exceptions
- try에 있는 모든 statement를 실행
- ValueError가 발생하면 except에 있는 명령문이 실행된다.
- 에러가 없으면 except는 실행되지 않는다
- 에러가 발생하더라도 except가 실행되고 나서 그다음 statement를 계속 실행한다
- else는 except이 발생하지 않을때 실행된다
try:
age = int(input("Age: "))
except ValueError as ex:
print("You didn't enter a valid age.")
print(ex) ## invalid literal for int() with base 10: 'a'
print(type(ex)) ## <class 'ValueError'>
else:
print("No exceptions were thrown.")
print("Execution continues.")
Handling Different Exceptions
- 다른 종류의 에러가 존재하는 경우
- except를 추가로 작성하면된다
- except 여러개 중 하나에 해당하면 다른 except는 실행되지 않는다
try:
age = int(input("Age: "))
xfactor = 10 / age
except ValueError:
print("You didn't enter a valid age.")
except ZeroDivisionError:
print("Age cannot be 0")
else:
print("No exceptions were thrown.")
print("Execution continues.")
try:
age = int(input("Age: "))
xfactor = 10 / age
except (ValueError, ZeroDivisionError):
print("You didn't enter a valid age.")
else:
print("No exceptions were thrown.")
print("Execution continues.")
Cleaning Up
- file 열기 등 다른 리소스를 가져다 쓸때는 항상 열었다가 close 해줘야한다.
- except, else에 중복으로 close를 선언하는건 비효율적이다.
- finally는 항상 실행되므로 활용할 수 있다.
try:
file = open("app.py")
age = int(input("Age: "))
xfactor = 10 / age
except (ValueError, ZeroDivisionError):
print("You didn't enter a valid age.")
else:
print("No exceptions were thrown.")
finally:
file.close()
The With Statement
- 파일 불러오기 등 다른 리소스를 참조해야하는 경우 with를 쓰면 된다
- with 구문 내용을 실행하고 나면 with가 알아서 close를 해주기 때문
- 여러 파일을 같이 작업해야한다면, ex app.py읽어서 another.txt에 쓰기를 한다거나, 여러개를 쓰면 된다
try:
with open("app.py") as file, open("another.txt") as target:
print ("File opened.")
age = int(input("Age: "))
xfactor = 10 / age
except (ValueError, ZeroDivisionError):
print("You didn't enter a valid age.")
else:
print("No exceptions were thrown.")
Raising Exceptions
- python3 built-in exception 검색하면 여러 exception을 확인할수 있다.
- raise를 쓰면 직접 에러를 정의할 수 있다.
- try 구문을 쓰지 않으면 프로그램이 에러 띄우고 죽어버린다
def calculate_xfactor(age):
if age <= 0:
raise ValueError("Age cannot be 0 or less.")
return 10 /age
try:
calcaulate_xfactor(-1)
except Value Error as error:
print(error)
0 댓글