Skip to content

Commit ac68538

Browse files
committed
Included Example of try/except/else/finally block w/ multiple exceptions raised
1 parent cf4d7e7 commit ac68538

File tree

1 file changed

+61
-3
lines changed

1 file changed

+61
-3
lines changed

09 Exceptions.ipynb

Lines changed: 61 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -47,11 +47,14 @@
4747
"```\n",
4848
"try:\n",
4949
" statements # Run this main action first\n",
50-
"except name1: # Run if name1 is raised during try block\n",
50+
"except name1: \n",
51+
" # Run if name1 is raised during try block\n",
5152
" statements\n",
52-
"except (name2, name3): # Run if any of these exceptions occur\n",
53+
"except (name2, name3): \n",
54+
" # Run if any of these exceptions occur\n",
5355
" statements \n",
54-
"except name4 as var: # Run if name4 is raised, assign instance raised to var \n",
56+
"except name4 as var: \n",
57+
" # Run if name4 is raised, assign instance raised to var \n",
5558
" statements\n",
5659
"except: # Run for all other exceptions raised\n",
5760
" statements\n",
@@ -60,6 +63,61 @@
6063
"```"
6164
]
6265
},
66+
{
67+
"cell_type": "code",
68+
"execution_count": 1,
69+
"metadata": {
70+
"collapsed": false,
71+
"scrolled": true
72+
},
73+
"outputs": [
74+
{
75+
"name": "stdout",
76+
"output_type": "stream",
77+
"text": [
78+
"[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, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]\n"
79+
]
80+
}
81+
],
82+
"source": [
83+
"list_of_numbers = [number for number in range(1, 100)]\n",
84+
"print(list_of_numbers)"
85+
]
86+
},
87+
{
88+
"cell_type": "code",
89+
"execution_count": 10,
90+
"metadata": {
91+
"collapsed": false
92+
},
93+
"outputs": [
94+
{
95+
"name": "stdout",
96+
"output_type": "stream",
97+
"text": [
98+
"Getting number at position 1 : 1\n",
99+
"Cleaning UP\n"
100+
]
101+
}
102+
],
103+
"source": [
104+
"dictionary_of_numbers = {}\n",
105+
"for number in list_of_numbers:\n",
106+
" dictionary_of_numbers[number**2] = number\n",
107+
" \n",
108+
"try:\n",
109+
" index = list_of_numbers.index(2)\n",
110+
" value = dictionary_of_numbers[index]\n",
111+
"except (ValueError, KeyError):\n",
112+
" print('Error Raised, but Controlled! ')\n",
113+
"else: \n",
114+
" # This executes ONLY if no exception is raised\n",
115+
" print('Getting number at position %d : %d' % (index, value))\n",
116+
"finally:\n",
117+
" # Do cleanup operations\n",
118+
" print('Cleaning UP')"
119+
]
120+
},
63121
{
64122
"cell_type": "markdown",
65123
"metadata": {},

0 commit comments

Comments
 (0)