-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path30thErrorHandlinginPython.py
More file actions
58 lines (29 loc) · 1011 Bytes
/
30thErrorHandlinginPython.py
File metadata and controls
58 lines (29 loc) · 1011 Bytes
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
# ! Error Handling
# * For Error handling, we use four blocks
# * try block contains the code contains the code that may throw an error (always needs 1 except or finally block after this)
# * except block contains the code to be run if an error is thrown in the try block (we can specify the error too)
# * else block contains the code to be run if no errors are raised
# * finally block which contains code which will run irrespective of any error is raised or not
try:
a = 3
b = a / 0
except NameError:
print('Variable doesn\'t exist')
except ZeroDivisionError:
print('Tried to divide by zero')
else:
print('Else code')
finally:
print('Finally Blocks always runs')
# ! Raise
# * We can raise errors by ourselves using the the raise keyword
try:
a = 4
b = 3
raise StopIteration # * Any error can be written here
except Exception as n:
print('Raised error',n)
else:
print('Runs when no error is raised')
finally:
print('Always runs')