[SECTION 09. 파이썬 기초 문법 - 예외 처리]
try ~ except 구문을 이용해 예외 상황을 처리할 수 있습니다.try:
실행할 코드
except 예외종류:
예외 발생 시 실행할 코드# try - except 없을 때
a = int(input("나눌 숫자 a: "))
b = int(input("나눌 숫자 b: "))
result = a / b
print("결과:", result)
# 예외 처리가 되어 있을 때
try:
a = int(input("나눌 숫자 a: "))
b = int(input("나눌 숫자 b: "))
result = a / b
print("결과:", result)
except ZeroDivisionError:
print("0으로 나눌 수 없습니다!")
except ValueError:
print("숫자를 입력해야 합니다!")
print("다음 코드...")
print("다음 코드...")
print("다음 코드...")
try:
data = [10, 20, 30]
index = int(input("인덱스 입력: "))
print("값:", data[index])
except IndexError:
print("인덱스 범위를 벗어났습니다.")
except ValueError:
print("숫자를 입력해야 합니다.")
finally: 예외 발생 여부와 관계없이 항상 실행되는 블록else: 예외가 발생하지 않았을 때 실행되는 블록try:
f = open("sample.txt", "w", encoding="utf-8")
f.write("예외 처리 테스트")
print("파일에 쓰기 완료")
except Exception as e:
print("에러 발생:", e)
finally:
f.close()
print("파일 닫기 완료")
try:
n = int(input("정수 입력: "))
except ValueError:
print("잘못된 입력입니다.")
else:
print("입력한 값:", n)
print("정상적으로 실행되었습니다.")
Exception 클래스를 상속 받아 구현합니다.class NegativeNumberError(Exception):
pass
def check_positive(n):
if n < 0:
raise NegativeNumberError("음수는 허용되지 않습니다.")
return n
try:
num = int(input("양수 입력: "))
print("입력 값:", check_positive(num))
except NegativeNumberError as e:
print("에러 발생:", e)
print() vs raise 차이점 정리| 항목 | print() | raise |
|---|---|---|
| 역할 | 텍스트(정보)를 출력 | 예외(오류)를 발생시킴 |
| 실행 결과 | 콘솔에 문자열만 출력 | 예외 발생 → 프로그램 흐름이 중단되거나 except로 이동 |
| 사용 목적 | 사용자 메시지 출력, 디버깅 | 오류 상황을 알리고, 처리 흐름을 제어함 |
| 예외 발생 여부 | ❌ 없음 | ✅ 예외 발생 |
| 흐름 제어 | 프로그램이 그대로 계속 실행됨 | 예외 발생 시 흐름이 중단되거나 예외 처리로 분기됨 |
| 사용 예시 | print("안녕하세요") | raise ValueError("잘못된 입력입니다.") |
class TooYoungError(Exception):
pass
def vote(age):
if age < 18:
raise TooYoungError("18세 미만은 투표할 수 없습니다.")
print("투표 가능합니다.")
try:
age = int(input("나이를 입력하세요: "))
vote(age)
except TooYoungError as e:
print("예외:", e)
def login(username, password):
if username == "" or password == "":
print("아이디와 비밀번호를 모두 입력하세요.")
return
if username == "admin" and password == "1234":
print("로그인 성공!")
else:
print("아이디 또는 비밀번호가 잘못되었습니다.")
# 실행
login("admin", "")
login("admin", "1234")
| 구분 | if문 제어 | 예외 처리 |
|---|---|---|
| 목적 | 조건에 따른 분기 | 오류나 특수 상황 알림 |
| 발생 시점 | 예측 가능 | 예측 불가 (비정상 흐름) |
| 처리 위치 | 현재 함수 내 | 호출한 쪽(상위 계층) |
| 코드 구조 | 단순 | 구조적, 확장성 있음 |
| 예시 | 로그인 실패, 입력값 누락 | 파일 없음, 연결 실패, 비즈니스 규칙 위반 |
사용자에게 두 수를 입력받아 나눗셈을 수행하세요.
숫자가 아닌 값을 입력하면 "숫자를 입력해야 합니다." 출력
0으로 나누면 "0으로 나눌 수 없습니다." 출력
정답
try:
num1 = int(input("첫 번째 정수: "))
num2 = int(input("두 번째 정수: "))
print(f"{num1} / {num2} = {num1 / num2}입니다.")
except ValueError:
print("숫자만 입력하세요.")
except ZeroDivisionError:
print("0으로는 나눌 수 없습니다.")
커스텀 예외 OverLimitError를 정의하고,
사용자가 입력한 점수가 100을 넘으면 예외를 발생시켜 "점수는 0~100 사이여야 합니다."를 출력하세요.
class OverLimitError(Exception):
pass
try:
score = int(input("점수 입력:"))
if score < 0 or score > 100:
raise OverLimitError('점수는 0 ~ 100점 사이여야 합니다.')
print("입력하신 점수는 ",score, "점입니다.", sep="")
except OverLimitError as e:
print("예외 발생:", e)
[SECTION 10. 학생 관리 프로그램 만들기 두 번째]
콘솔에서 명령어를 입력받아 학생 정보를 관리하는 프로그램을 만드세요.
학생은 이름(name), 나이(age), 점수(score) 정보를 가집니다.
students = [None, None, None]count 변수를 사용한다.프로그램은 무한 반복으로 아래 메뉴를 출력한다.
1. 학생 등록2. 학생 목록3. 학생 검색4. 학생 수정5. 학생 삭제0. 종료count가 3이면 "학생 수를 초과하였습니다." 출력 후 등록 불가students[count]에 저장count += 11번) 이름: 홍길동 / 나이: 20 / 점수: 80"존재하지 않는 학생입니다.""존재하지 않는 학생입니다."==== n번째 학생 수정이 완료되었습니다 ===="존재하지 않는 학생입니다."None으로 만들고 count -= 1"잘못된 명령어입니다." 출력class Student:
"""학생 한 명의 정보를 담는 클래스"""
def __init__(self, name, age, score):
self.name = name
self.age = age
self.score = score
def __str__(self):
return f"이름:{self.name} / 나이:{self.age}살 / 점수:{self.score}점"
class StudentManager:
"""학생 목록을 관리하는 클래스"""
MAX_COUNT = 4 # 기존 코드의 'count > 3'과 동일한 등록 제한 조건
def __init__(self):
self.students = []
def find_student(self, name):
"""이름으로 학생을 찾아서 반환 (없으면 None)"""
# 아래에 코드 작성
def add_student(self):
if len(self.students) > self.MAX_COUNT - 1:
print("더 이상 등록할 수 없습니다.")
return
name = input("이름 입력:")
age = int(input("나이 입력:"))
score = int(input("점수 입력:"))
student = Student(name, age, score)
self.students.append(student)
def list_students(self):
if not self.students:
print("등록된 학생이 없습니다.")
return
print()
print("=== 학생 목록 ===")
# 아래에 코드 작성
for student in self.students:
print(student)
def search_student(self):
if not self.students:
print("등록된 학생이 없습니다.")
return
search_name = input("검색할 학생 이름:")
# 해당 학생의 존재 여부
flag = False
# 찾은 학생의 객체 정보
search_student = None
for student in self.students:
if search_name == student.name:
flag = True # 해당 학생이 존재함
search_student = student # 이름이 일치하는 학생의 객체 정보를 넣어줌
if not flag:
print("해당 학생은 존재하지 않습니다.")
return
else:
print(search_student)
def modify_student(self):
if not self.students:
print("등록된 학생이 없습니다.")
return
modify_name = input("수정할 학생 이름:")
# 해당 학생의 존재 여부
flag = False
idx = 0
# 찾은 학생의 객체 정보
modify_student = None
for student in self.students:
if modify_name == student.name:
idx += 1
flag = True # 해당 학생이 존재함
modify_student = student # 이름이 일치하는 학생의 객체 정보를 넣어줌
if not flag:
print("해당 학생은 존재하지 않습니다.")
return
else:
# 학생이 존재함
new_name = input("변경할 이름:") # 김수한
if new_name == "":
new_name = modify_student.name
new_age = input("변경할 나이:")
if new_age == "":
new_age = modify_student.age
else:
new_age = int(new_age)
new_score = int(input("변경할 점수:"))
if new_score == "":
new_score = modify_student.score
else:
new_score = int(new_score)
self.students.insert(idx, Student(new_name, new_age, new_score))
def delete_student(self):
if not self.students:
print("등록된 학생이 없습니다.")
return
delete_name = input("삭제할 학생 이름:")
student = self.find_student(delete_name)
if student:
self.students.remove(student)
print("학생을 삭제하였습니다.")
else:
print("존재하지 않는 학생입니다.")
def print_menu(self):
print("1. 학생 등록")
print("2. 학생 목록")
print("3. 학생 검색")
print("4. 학생 수정")
print("5. 학생 삭제")
print("0. 프로그램 종료")
def run(self):
while True:
self.print_menu()
cmd = int(input("명령어 입력:"))
if cmd == 1:
self.add_student()
elif cmd == 2:
self.list_students()
elif cmd == 3:
self.search_student()
elif cmd == 4:
self.modify_student()
elif cmd == 5:
self.delete_student()
elif cmd == 0:
print("프로그램을 종료합니다.")
break
if __name__ == "__main__":
manager = StudentManager()
manager.run()