-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path11-oop_errors.py
More file actions
73 lines (59 loc) · 1.48 KB
/
Copy path11-oop_errors.py
File metadata and controls
73 lines (59 loc) · 1.48 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
66
67
68
69
70
71
72
73
"""
# syntax
try:
dangerous_code()
except SomeError:
handle_the_error()
else:
handle_no_error()
finally:
do_no_matter_what()
# Bare except blocks
def read_int():
while True:
try:
return int(input("Pleae give me a number: "))
except:
print("Not a number!")
'''
A bare except block captures all exceptions, including subclasses of BaseException like KeyboardInterrupt
or SystemExit! This means that you almost never want except: and instead want to capture a specific class
of errors, like except ValueError:
'''
"""
# capture the ValueError specifically
def read_int():
while True:
try:
return int(input("Pleae give me a number: "))
except ValueError:
print("Not a number!")
read_int()
# except and else blocks
try:
distance = int(input("How far? "))
car.travel(distance)
car.rev()
except ValueError as e:
print(e)
except ZeroDivisionError:
print("Bad division")
except (NameError, AttributeError):
print("Bad name or attribute.")
else:
print("success")
'''
# example only
try:
update_the_database()
except TransactionError:
rollback()
else:
commit()
'''
# The finally block runs almost no matter what.
# It's used to define unconditional clean-up actions, such as closing a file or releasing a system resource.
try:
raise NotImplementedError
finally:
print("GoodBye!")