여러 예외 처리하기
Coddy Python 여정의 논리와 흐름 섹션에 포함된 레슨. 78개 중 65번째.
Python에서는 서로 다른 유형의 exceptions를 별도의 except 블록에서 처리할 수 있습니다. 이를 통해 발생한 특정 error에 따라 다르게 대응할 수 있습니다.
기본적인 try-except 구조로 시작하세요:
try:
# 예외를 발생시킬 수 있는 코드
pass
except Exception as e:
# 모든 예외 처리
pass여러 exceptions를 처리하려면 구체적인 except 블록을 추가하세요:
try:
number = int(input("Enter a number: "))
result = 10 / number
print(result)
except ValueError:
print("That's not a valid number!")
except ZeroDivisionError:
print("Cannot divide by zero!")하나의 except 블록에서 여러 exception 유형을 catch할 수도 있습니다:
try:
# 일부 코드
pass
except (ValueError, TypeError):
print("Invalid input type!")except 블록의 순서는 중요합니다. 항상 더 구체적인 예외를 더 일반적인 예외보다 먼저 배치하세요.
챌린지
쉬움process_data라는 함수를 생성하세요. 이 함수는 다음을 수행합니다:
- 잠재적인 데이터를 나타내는 string input을 받습니다.
- 이를 integer로 convert한 다음, 해당 integer로 100을 divided합니다.
- result를 반환합니다.
- 최소 3개의 가능한 exceptions를 처리합니다:
- input을 integer로 convert할 수 없는 경우의
ValueError("Input must be a number!"를 print) - input이 0인 경우의
ZeroDivisionError("Cannot divide by zero!"를 print) - generic handler를 사용하는 any other exception ("An unexpected error occurred!"를 print)
- input을 integer로 convert할 수 없는 경우의
직접 해보기
def process_data(input_string):
try:
# 입력 문자열을 정수로 변환 시도
# 입력 값으로 100을 나눈 값을 계산
# 결과 반환
except ValueError:
# 입력을 정수로 변환할 수 없는 경우 처리
except ZeroDivisionError:
# 입력이 0인 경우 처리
except:
# 기타 예상치 못한 예외 처리
return None이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
논리와 흐름의 모든 레슨
직접 연습해 보세요: 온라인 Python 컴파일러