흔히 보는 오류
- **`ZeroDivisionError`**: 0으로 나누려고 할 때.
- **`NameError`**: 로컬 또는 글로벌 이름을 찾을 수 없을 때.
- **`TypeError`**: 연산이나 함수가 부적절한 타입의 객체에 적용될 때.
- **`IndexError`** 및 **`KeyError -**: 시퀀스 인덱스나 사전 키가 범위 밖일 때.
- **`FileNotFoundError`**: 요청한 파일이나 디렉토리를 찾을 수 없을 때.
- **`ValueError`**: 연산이나 함수가 적절한 타입의 객체에 적용되었지만, 그 객체가 부적절한 값을 가지고 있을 때.
try:
with open("test.txt", "r") as f:
content = f.read()
print(content)
except FileNotFoundError:
print("파일이 안열려요.")
finally:
print("작업 완료.")
finally를 통해서는 에러가 났을 때 어떻게 할지 처리할 수 있다.
file_list = ['test.txt', 'test1.txt', 'test2.txt']
for file_name in file_list:
try:
with open(file_name, 'r') as f:
content = f.read()
number = int(content)
print(number**2)
print(number/0)
except FileNotFoundError:
print('파일을 찾을 수 없어요. 확인해주세요.')
except ValueError:
print('내용을 확인해 주세요.')
except Exception as e: #에러 발생시 무슨 에러인지 출력해주고 프로그램 안죽음.
print(e) #보통 마지막에 써줌.
print(f"{e}에러 발생했습니다.")
except Exception as e: 이 코드는 발생한 오류를 e에 넣어준다.
그래서 print(e)를 해주면 내가 대비하지 못한 에러가 뭔지 출력해준다.