Repository navigation
Expand file tree
/
Copy pathexceptionEx2.py
More file actions
65 lines (52 loc) · 1.93 KB
/
Copy pathexceptionEx2.py
File metadata and controls
65 lines (52 loc) · 1.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# 예외를 직접 일으키기, 그리고 나쁜 예외 처리
print('---------- raise : 직접 예외를 낸다 ----------')
def set_age(age):
if not isinstance(age, int):
raise TypeError('나이는 정수여야 합니다')
if age < 0:
raise ValueError('나이는 0 이상이어야 합니다')
return age
for value in [23, -5, '스물셋']:
try:
print('설정 :', set_age(value))
except (TypeError, ValueError) as e:
print(f'거부 : {type(e).__name__} - {e}')
print('---------- 내 예외 만들기 ----------')
class InsufficientBalanceError(Exception):
"""잔액이 부족할 때."""
def withdraw(balance, amount):
if amount > balance:
raise InsufficientBalanceError(f'잔액 {balance}, 요청 {amount}')
return balance - amount
try:
withdraw(1000, 5000)
except InsufficientBalanceError as e:
print('출금 실패 :', e)
print('---------- 나쁜 예 1 : 전부 삼키기 ----------')
def bad(text):
try:
return 100 / int(text)
except Exception: # 무엇이 잘못됐는지 알 수 없다
print(' 에러가 났습니다')
bad('0') # ZeroDivisionError 인데
bad('abc') # ValueError 인데 — 메시지가 똑같다
# test/class_ex_01.py 가 바로 이 함정에 빠져 있었습니다.
print('---------- 나쁜 예 2 : 통째로 무시 ----------')
def worse(text):
try:
return 100 / int(text)
except Exception:
pass # 아무 일도 없었다는 듯이 넘어간다 — 최악
print(' worse 반환값 :', worse('abc')) # None 이 조용히 돌아온다
print('---------- 좋은 예 ----------')
def good(text):
try:
return 100 / int(text)
except ValueError:
print(f' "{text}" 는 숫자가 아닙니다')
except ZeroDivisionError:
print(' 0으로 나눌 수 없습니다')
good('0')
good('abc')
good('4')
print(' good 정상값 :', good('4'))