-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path28 - TryExcept.py
More file actions
74 lines (62 loc) · 1.85 KB
/
28 - TryExcept.py
File metadata and controls
74 lines (62 loc) · 1.85 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
74
"""
The "try" block lets you test a block of code for errors.
The "except" block lets you handle the error.
The "else" block lets you execute code when there is no error.
The "finally" block lets you execute code, regardless of the result of the try- and except blocks
"""
# Exception Handling
"""
When an error occurs, or exception as we call it, Python will normally stop and
generate an error message.
These exceptions can be handled using the try statement
"""
try:
print(x)
except:
print("An exception occurred")
# or
try:
print(x)
except NameError:
print("Variable x is not defined")
except:
print("Something else went wrong")
# Else
"""You can use the else keyword to define a block of code to be executed if no errors were raised"""
try:
print("Hello")
except:
print("Something went wrong")
else:
print("Nothing went wrong")
# Finally
"""The finally block, if specified, will be executed regardless if the try block raises an error or not
"""
try:
print(x)
except:
print("Something went wrong")
finally:
print("The 'try except' is finished")
"""This can be useful to close objects and clean up resources"""
try:
f = open("demofile.txt") # a file that is not writeable
try:
f.write("Lorum Ipsum")
except:
print("Something went wrong when writing to the file")
finally:
f.close()
except:
print("Something went wrong when opening the file")
# Raise an exception
"""As a Python developer you can choose to throw an exception if a condition occurs.
To throw (or raise) an exception, use the raise keyword"""
x = -1
if x < 0:
raise Exception("Sorry, no numbers below zero")
"""The raise keyword is used to raise an exception.
You can define what kind of error to raise, and the text to print to the user"""
x = "hello"
if not type(x) is int:
raise TypeError("Only integers are allowed")