-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathexceptions.html
More file actions
340 lines (309 loc) · 82.4 KB
/
exceptions.html
File metadata and controls
340 lines (309 loc) · 82.4 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
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Python - Exceptions</title>
<meta name="generator" content="VuePress 1.8.2">
<link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png">
<link rel="manifest" href="/site.webmanifest">
<link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png">
<link rel="mask-icon" href="/safari-pinned-tab.svg" color="#5bbad5">
<meta name="description" content="Do not catch everything!, Re-raising exceptions, Catching multiple exceptions, Catching Exceptions, Exception Hierarchy, Else, Raising Exceptions, Creating custom exception types, Exceptions are Objects too, Practical examples of exception handling, Running clean-up code with finally, Chain exceptions with raise from">
<meta property="og:site_name" content="DevTut">
<meta property="og:title" content="Python - Exceptions">
<meta property="og:description" content="Do not catch everything!, Re-raising exceptions, Catching multiple exceptions, Catching Exceptions, Exception Hierarchy, Else, Raising Exceptions, Creating custom exception types, Exceptions are Objects too, Practical examples of exception handling, Running clean-up code with finally, Chain exceptions with raise from">
<meta property="og:type" content="article">
<meta property="og:url" content="/python/exceptions.html">
<meta property="og:image" content="/logo.png">
<meta name="twitter:title" content="Python - Exceptions">
<meta name="twitter:description" content="Do not catch everything!, Re-raising exceptions, Catching multiple exceptions, Catching Exceptions, Exception Hierarchy, Else, Raising Exceptions, Creating custom exception types, Exceptions are Objects too, Practical examples of exception handling, Running clean-up code with finally, Chain exceptions with raise from">
<meta name="twitter:url" content="/python/exceptions.html">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:image" content="/logo.png">
<meta name="theme-color" content="#ffffff">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<meta name="msapplication-TileImage" content="/mstile-150x150.png">
<meta name="msapplication-TileColor" content="#da532c">
<meta name="google-site-verification" content="76_rKXgwMVIjd-axJC_1zPV9OS4mEjvtgjYOWVkAdnQ">
<link rel="preload" href="/assets/css/0.styles.60619e34.css" as="style"><link rel="preload" href="/assets/js/app.1779e102.js" as="script"><link rel="preload" href="/assets/js/3.2cfa8016.js" as="script"><link rel="preload" href="/assets/js/2702.5705e114.js" as="script">
<link rel="stylesheet" href="/assets/css/0.styles.60619e34.css">
</head>
<body>
<div id="app" data-server-rendered="true"><div class="theme-container"><header class="navbar"><div class="sidebar-button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" role="img" viewBox="0 0 448 512" class="icon"><path fill="currentColor" d="M436 124H12c-6.627 0-12-5.373-12-12V80c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12zm0 160H12c-6.627 0-12-5.373-12-12v-32c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12zm0 160H12c-6.627 0-12-5.373-12-12v-32c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12z"></path></svg></div> <a href="/" class="home-link router-link-active"><!----> <span class="site-name">DevTut</span></a> <div class="links"><form id="search-form" role="search" class="algolia-search-wrapper search-box"><input id="algolia-search-input" class="search-query"></form> <nav class="nav-links can-hide"> <a href="https://github.com/devtut/generate" target="_blank" rel="noopener noreferrer" class="repo-link">
GitHub
<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a></nav></div></header> <div class="sidebar-mask"></div> <aside class="sidebar"><nav class="nav-links"> <a href="https://github.com/devtut/generate" target="_blank" rel="noopener noreferrer" class="repo-link">
GitHub
<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a></nav> <ul class="sidebar-links"><li><section class="sidebar-group depth-0"><p class="sidebar-heading open"><span>Python</span> <!----></p> <ul class="sidebar-links sidebar-group-items"><li><a href="/python/" aria-current="page" class="sidebar-link">Disclaimer</a></li><li><a href="/python/getting-started-with-python-language.html" class="sidebar-link">Getting started with Python Language</a></li><li><a href="/python/python-data-types.html" class="sidebar-link">Python Data Types</a></li><li><a href="/python/indentation.html" class="sidebar-link">Indentation</a></li><li><a href="/python/comments-and-documentation.html" class="sidebar-link">Comments and Documentation</a></li><li><a href="/python/date-and-time.html" class="sidebar-link">Date and Time</a></li><li><a href="/python/enum.html" class="sidebar-link">Enum</a></li><li><a href="/python/set.html" class="sidebar-link">Set</a></li><li><a href="/python/simple-mathematical-operators.html" class="sidebar-link">Simple Mathematical Operators</a></li><li><a href="/python/bitwise-operators.html" class="sidebar-link">Bitwise Operators</a></li><li><a href="/python/boolean-operators.html" class="sidebar-link">Boolean Operators</a></li><li><a href="/python/operator-precedence.html" class="sidebar-link">Operator Precedence</a></li><li><a href="/python/variable-scope-and-binding.html" class="sidebar-link">Variable Scope and Binding</a></li><li><a href="/python/conditionals.html" class="sidebar-link">Conditionals</a></li><li><a href="/python/comparisons.html" class="sidebar-link">Comparisons</a></li><li><a href="/python/loops.html" class="sidebar-link">Loops</a></li><li><a href="/python/arrays.html" class="sidebar-link">Arrays</a></li><li><a href="/python/multidimensional-arrays.html" class="sidebar-link">Multidimensional arrays</a></li><li><a href="/python/dictionary.html" class="sidebar-link">Dictionary</a></li><li><a href="/python/list.html" class="sidebar-link">List</a></li><li><a href="/python/list-comprehensions.html" class="sidebar-link">List Comprehensions</a></li><li><a href="/python/list-slicing-selecting-parts-of-lists.html" class="sidebar-link">List slicing (selecting parts of lists)</a></li><li><a href="/python/groupby.html" class="sidebar-link">groupby()</a></li><li><a href="/python/linked-lists.html" class="sidebar-link">Linked lists</a></li><li><a href="/python/linked-list-node.html" class="sidebar-link">Linked List Node</a></li><li><a href="/python/filter.html" class="sidebar-link">Filter</a></li><li><a href="/python/heapq.html" class="sidebar-link">Heapq</a></li><li><a href="/python/tuple.html" class="sidebar-link">Tuple</a></li><li><a href="/python/basic-input-and-output.html" class="sidebar-link">Basic Input and Output</a></li><li><a href="/python/files-folders-i-o.html" class="sidebar-link">Files & Folders I/O</a></li><li><a href="/python/os-path.html" class="sidebar-link">os.path</a></li><li><a href="/python/iterables-and-iterators.html" class="sidebar-link">Iterables and Iterators</a></li><li><a href="/python/functions.html" class="sidebar-link">Functions</a></li><li><a href="/python/defining-functions-with-list-arguments.html" class="sidebar-link">Defining functions with list arguments</a></li><li><a href="/python/functional-programming-in-python.html" class="sidebar-link">Functional Programming in Python</a></li><li><a href="/python/partial-functions.html" class="sidebar-link">Partial functions</a></li><li><a href="/python/decorators.html" class="sidebar-link">Decorators</a></li><li><a href="/python/classes.html" class="sidebar-link">Classes</a></li><li><a href="/python/metaclasses.html" class="sidebar-link">Metaclasses</a></li><li><a href="/python/string-formatting.html" class="sidebar-link">String Formatting</a></li><li><a href="/python/string-methods.html" class="sidebar-link">String Methods</a></li><li><a href="/python/using-loops-within-functions.html" class="sidebar-link">Using loops within functions</a></li><li><a href="/python/importing-modules.html" class="sidebar-link">Importing modules</a></li><li><a href="/python/difference-between-module-and-package.html" class="sidebar-link">Difference between Module and Package</a></li><li><a href="/python/math-module.html" class="sidebar-link">Math Module</a></li><li><a href="/python/complex-math.html" class="sidebar-link">Complex math</a></li><li><a href="/python/collections-module.html" class="sidebar-link">Collections module</a></li><li><a href="/python/operator-module.html" class="sidebar-link">Operator module</a></li><li><a href="/python/json-module.html" class="sidebar-link">JSON Module</a></li><li><a href="/python/sqlite3-module.html" class="sidebar-link">Sqlite3 Module</a></li><li><a href="/python/the-os-module.html" class="sidebar-link">The os Module</a></li><li><a href="/python/the-locale-module.html" class="sidebar-link">The locale Module</a></li><li><a href="/python/itertools-module.html" class="sidebar-link">Itertools Module</a></li><li><a href="/python/asyncio-module.html" class="sidebar-link">Asyncio Module</a></li><li><a href="/python/random-module.html" class="sidebar-link">Random module</a></li><li><a href="/python/functools-module.html" class="sidebar-link">Functools Module</a></li><li><a href="/python/the-dis-module.html" class="sidebar-link">The dis module</a></li><li><a href="/python/the-base64-module.html" class="sidebar-link">The base64 Module</a></li><li><a href="/python/queue-module.html" class="sidebar-link">Queue Module</a></li><li><a href="/python/deque-module.html" class="sidebar-link">Deque Module</a></li><li><a href="/python/webbrowser-module.html" class="sidebar-link">Webbrowser Module</a></li><li><a href="/python/tkinter.html" class="sidebar-link">tkinter</a></li><li><a href="/python/pyautogui-module.html" class="sidebar-link">pyautogui module</a></li><li><a href="/python/indexing-and-slicing.html" class="sidebar-link">Indexing and Slicing</a></li><li><a href="/python/plotting-with-matplotlib.html" class="sidebar-link">Plotting with Matplotlib</a></li><li><a href="/python/graph-tool.html" class="sidebar-link">graph-tool</a></li><li><a href="/python/generators.html" class="sidebar-link">Generators</a></li><li><a href="/python/reduce.html" class="sidebar-link">Reduce</a></li><li><a href="/python/map-function.html" class="sidebar-link">Map Function</a></li><li><a href="/python/exponentiation.html" class="sidebar-link">Exponentiation</a></li><li><a href="/python/searching.html" class="sidebar-link">Searching</a></li><li><a href="/python/sorting-minimum-and-maximum.html" class="sidebar-link">Sorting, Minimum and Maximum</a></li><li><a href="/python/counting.html" class="sidebar-link">Counting</a></li><li><a href="/python/the-print-function.html" class="sidebar-link">The Print Function</a></li><li><a href="/python/regular-expressions-regex.html" class="sidebar-link">Regular Expressions (Regex)</a></li><li><a href="/python/copying-data.html" class="sidebar-link">Copying data</a></li><li><a href="/python/context-managers-with-statement.html" class="sidebar-link">Context Managers (“with” Statement)</a></li><li><a href="/python/the-name-special-variable.html" class="sidebar-link">The _name_ special variable</a></li><li><a href="/python/checking-path-existence-and-permissions.html" class="sidebar-link">Checking Path Existence and Permissions</a></li><li><a href="/python/creating-python-packages.html" class="sidebar-link">Creating Python packages</a></li><li><a href="/python/usage-of-pip-module-pypi-package-manager.html" class="sidebar-link">Usage of "pip" module: PyPI Package Manager</a></li><li><a href="/python/pip-pypi-package-manager.html" class="sidebar-link">pip: PyPI Package Manager</a></li><li><a href="/python/parsing-command-line-arguments.html" class="sidebar-link">Parsing Command Line arguments</a></li><li><a href="/python/subprocess-library.html" class="sidebar-link">Subprocess Library</a></li><li><a href="/python/setup-py.html" class="sidebar-link">setup.py</a></li><li><a href="/python/recursion.html" class="sidebar-link">Recursion</a></li><li><a href="/python/type-hints.html" class="sidebar-link">Type Hints</a></li><li><a href="/python/exceptions.html" aria-current="page" class="active sidebar-link">Exceptions</a><ul class="sidebar-sub-headers"><li class="sidebar-sub-header"><a href="/python/exceptions.html#do-not-catch-everything" class="sidebar-link">Do not catch everything!</a></li><li class="sidebar-sub-header"><a href="/python/exceptions.html#re-raising-exceptions" class="sidebar-link">Re-raising exceptions</a></li><li class="sidebar-sub-header"><a href="/python/exceptions.html#catching-multiple-exceptions" class="sidebar-link">Catching multiple exceptions</a></li><li class="sidebar-sub-header"><a href="/python/exceptions.html#catching-exceptions" class="sidebar-link">Catching Exceptions</a></li><li class="sidebar-sub-header"><a href="/python/exceptions.html#exception-hierarchy" class="sidebar-link">Exception Hierarchy</a></li><li class="sidebar-sub-header"><a href="/python/exceptions.html#else" class="sidebar-link">Else</a></li><li class="sidebar-sub-header"><a href="/python/exceptions.html#raising-exceptions" class="sidebar-link">Raising Exceptions</a></li><li class="sidebar-sub-header"><a href="/python/exceptions.html#creating-custom-exception-types" class="sidebar-link">Creating custom exception types</a></li><li class="sidebar-sub-header"><a href="/python/exceptions.html#exceptions-are-objects-too" class="sidebar-link">Exceptions are Objects too</a></li><li class="sidebar-sub-header"><a href="/python/exceptions.html#practical-examples-of-exception-handling" class="sidebar-link">Practical examples of exception handling</a></li><li class="sidebar-sub-header"><a href="/python/exceptions.html#running-clean-up-code-with-finally" class="sidebar-link">Running clean-up code with finally</a></li><li class="sidebar-sub-header"><a href="/python/exceptions.html#chain-exceptions-with-raise-from" class="sidebar-link">Chain exceptions with raise from</a></li></ul></li><li><a href="/python/raise-custom-errors-exceptions.html" class="sidebar-link">Raise Custom Errors / Exceptions</a></li><li><a href="/python/commonwealth-exceptions.html" class="sidebar-link">Commonwealth Exceptions</a></li><li><a href="/python/urllib.html" class="sidebar-link">urllib</a></li><li><a href="/python/web-scraping-with-python.html" class="sidebar-link">Web scraping with Python</a></li><li><a href="/python/html-parsing.html" class="sidebar-link">HTML Parsing</a></li><li><a href="/python/manipulating-xml.html" class="sidebar-link">Manipulating XML</a></li><li><a href="/python/python-requests-post.html" class="sidebar-link">Python Requests Post</a></li><li><a href="/python/distribution.html" class="sidebar-link">Distribution</a></li><li><a href="/python/property-objects.html" class="sidebar-link">Property Objects</a></li><li><a href="/python/overloading.html" class="sidebar-link">Overloading</a></li><li><a href="/python/polymorphism.html" class="sidebar-link">Polymorphism</a></li><li><a href="/python/method-overriding.html" class="sidebar-link">Method Overriding</a></li><li><a href="/python/user-defined-methods.html" class="sidebar-link">User-Defined Methods</a></li><li><a href="/python/string-representations-of-class-instances-str-and-repr-methods.html" class="sidebar-link">String representations of class instances: _str and repr_ methods</a></li><li><a href="/python/debugging.html" class="sidebar-link">Debugging</a></li><li><a href="/python/reading-and-writing-csv.html" class="sidebar-link">Reading and Writing CSV</a></li><li><a href="/python/writing-to-csv-from-string-or-list.html" class="sidebar-link">Writing to CSV from String or List</a></li><li><a href="/python/dynamic-code-execution-with-exec-and-eval.html" class="sidebar-link">Dynamic code execution with exec and eval</a></li><li><a href="/python/pyinstaller-distributing-python-code.html" class="sidebar-link">PyInstaller - Distributing Python Code</a></li><li><a href="/python/data-visualization-with-python.html" class="sidebar-link">Data Visualization with Python</a></li><li><a href="/python/the-interpreter-command-line-console.html" class="sidebar-link">The Interpreter (Command Line Console)</a></li><li><a href="/python/args-and-kwargs.html" class="sidebar-link">args and *kwargs</a></li><li><a href="/python/garbage-collection.html" class="sidebar-link">Garbage Collection</a></li><li><a href="/python/pickle-data-serialisation.html" class="sidebar-link">Pickle data serialisation</a></li><li><a href="/python/binary-data.html" class="sidebar-link">Binary Data</a></li><li><a href="/python/idioms.html" class="sidebar-link">Idioms</a></li><li><a href="/python/data-serialization.html" class="sidebar-link">Data Serialization</a></li><li><a href="/python/multiprocessing.html" class="sidebar-link">Multiprocessing</a></li><li><a href="/python/multithreading.html" class="sidebar-link">Multithreading</a></li><li><a href="/python/processes-and-threads.html" class="sidebar-link">Processes and Threads</a></li><li><a href="/python/python-concurrency.html" class="sidebar-link">Python concurrency</a></li><li><a href="/python/parallel-computation.html" class="sidebar-link">Parallel computation</a></li><li><a href="/python/sockets.html" class="sidebar-link">Sockets</a></li><li><a href="/python/websockets.html" class="sidebar-link">Websockets</a></li><li><a href="/python/sockets-and-message-encryption-decryption-between-client-and-server.html" class="sidebar-link">Sockets And Message Encryption/Decryption Between Client and Server</a></li><li><a href="/python/python-networking.html" class="sidebar-link">Python Networking</a></li><li><a href="/python/python-http-server.html" class="sidebar-link">Python HTTP Server</a></li><li><a href="/python/flask.html" class="sidebar-link">Flask</a></li><li><a href="/python/introduction-to-rabbitmq-using-amqpstorm.html" class="sidebar-link">Introduction to RabbitMQ using AMQPStorm</a></li><li><a href="/python/descriptor.html" class="sidebar-link">Descriptor</a></li><li><a href="/python/tempfile-namedtemporaryfile.html" class="sidebar-link">tempfile NamedTemporaryFile</a></li><li><a href="/python/input-subset-and-output-external-data-files-using-pandas.html" class="sidebar-link">Input, Subset and Output External Data Files using Pandas</a></li><li><a href="/python/unzipping-files.html" class="sidebar-link">Unzipping Files</a></li><li><a href="/python/working-with-zip-archives.html" class="sidebar-link">Working with ZIP archives</a></li><li><a href="/python/getting-start-with-gzip.html" class="sidebar-link">getting start with GZip</a></li><li><a href="/python/stack.html" class="sidebar-link">Stack</a></li><li><a href="/python/working-around-the-global-interpreter-lock-gil.html" class="sidebar-link">Working around the Global Interpreter Lock (GIL)</a></li><li><a href="/python/deployment.html" class="sidebar-link">Deployment</a></li><li><a href="/python/logging.html" class="sidebar-link">Logging</a></li><li><a href="/python/web-server-gateway-interface-wsgi.html" class="sidebar-link">Web Server Gateway Interface (WSGI)</a></li><li><a href="/python/python-server-sent-events.html" class="sidebar-link">Python Server Sent Events</a></li><li><a href="/python/alternatives-to-switch-statement-from-other-languages.html" class="sidebar-link">Alternatives to switch statement from other languages</a></li><li><a href="/python/list-destructuring-aka-packing-and-unpacking.html" class="sidebar-link">List destructuring (aka packing and unpacking)</a></li><li><a href="/python/accessing-python-source-code-and-bytecode.html" class="sidebar-link">Accessing Python source code and bytecode</a></li><li><a href="/python/mixins.html" class="sidebar-link">Mixins</a></li><li><a href="/python/attribute-access.html" class="sidebar-link">Attribute Access</a></li><li><a href="/python/arcpy.html" class="sidebar-link">ArcPy</a></li><li><a href="/python/abstract-base-classes-abc.html" class="sidebar-link">Abstract Base Classes (abc)</a></li><li><a href="/python/plugin-and-extension-classes.html" class="sidebar-link">Plugin and Extension Classes</a></li><li><a href="/python/immutable-datatypes-int-float-str-tuple-and-frozensets.html" class="sidebar-link">Immutable datatypes(int, float, str, tuple and frozensets)</a></li><li><a href="/python/incompatibilities-moving-from-python-2-to-python-3.html" class="sidebar-link">Incompatibilities moving from Python 2 to Python 3</a></li><li><a href="/python/2to3-tool.html" class="sidebar-link">2to3 tool</a></li><li><a href="/python/non-official-python-implementations.html" class="sidebar-link">Non-official Python implementations</a></li><li><a href="/python/abstract-syntax-tree.html" class="sidebar-link">Abstract syntax tree</a></li><li><a href="/python/unicode-and-bytes.html" class="sidebar-link">Unicode and bytes</a></li><li><a href="/python/python-serial-communication-pyserial.html" class="sidebar-link">Python Serial Communication (pyserial)</a></li><li><a href="/python/neo4j-and-cypher-using-py2neo.html" class="sidebar-link">Neo4j and Cypher using Py2Neo</a></li><li><a href="/python/basic-curses-with-python.html" class="sidebar-link">Basic Curses with Python</a></li><li><a href="/python/templates-in-python.html" class="sidebar-link">Templates in python</a></li><li><a href="/python/pillow.html" class="sidebar-link">Pillow</a></li><li><a href="/python/the-pass-statement.html" class="sidebar-link">The pass statement</a></li><li><a href="/python/cli-subcommands-with-precise-help-output.html" class="sidebar-link">CLI subcommands with precise help output</a></li><li><a href="/python/database-access.html" class="sidebar-link">Database Access</a></li><li><a href="/python/connecting-python-to-sql-server.html" class="sidebar-link">Connecting Python to SQL Server</a></li><li><a href="/python/postgresql.html" class="sidebar-link">PostgreSQL</a></li><li><a href="/python/python-and-excel.html" class="sidebar-link">Python and Excel</a></li><li><a href="/python/turtle-graphics.html" class="sidebar-link">Turtle Graphics</a></li><li><a href="/python/python-persistence.html" class="sidebar-link">Python Persistence</a></li><li><a href="/python/design-patterns.html" class="sidebar-link">Design Patterns</a></li><li><a href="/python/hashlib.html" class="sidebar-link">hashlib</a></li><li><a href="/python/creating-a-windows-service-using-python.html" class="sidebar-link">Creating a Windows service using Python</a></li><li><a href="/python/mutable-vs-immutable-and-hashable-in-python.html" class="sidebar-link">Mutable vs Immutable (and Hashable) in Python</a></li><li><a href="/python/configparser.html" class="sidebar-link">configparser</a></li><li><a href="/python/optical-character-recognition.html" class="sidebar-link">Optical Character Recognition</a></li><li><a href="/python/virtual-environments.html" class="sidebar-link">Virtual environments</a></li><li><a href="/python/python-virtual-environment-virtualenv.html" class="sidebar-link">Python Virtual Environment - virtualenv</a></li><li><a href="/python/virtual-environment-with-virtualenvwrapper.html" class="sidebar-link">virtual environment with virtualenvwrapper</a></li><li><a href="/python/create-virtual-environment-with-virtualenvwrapper-in-windows.html" class="sidebar-link">Create virtual environment with virtualenvwrapper in windows</a></li><li><a href="/python/sys.html" class="sidebar-link">sys</a></li><li><a href="/python/chempy-python-package.html" class="sidebar-link">ChemPy - python package</a></li><li><a href="/python/pygame.html" class="sidebar-link">pygame</a></li><li><a href="/python/pyglet.html" class="sidebar-link">Pyglet</a></li><li><a href="/python/audio.html" class="sidebar-link">Audio</a></li><li><a href="/python/pyaudio.html" class="sidebar-link">pyaudio</a></li><li><a href="/python/shelve.html" class="sidebar-link">shelve</a></li><li><a href="/python/iot-programming-with-python-and-raspberry-pi.html" class="sidebar-link">IoT Programming with Python and Raspberry PI</a></li><li><a href="/python/kivy-cross-platform-python-framework-for-nui-development.html" class="sidebar-link">kivy - Cross-platform Python Framework for NUI Development</a></li><li><a href="/python/pandas-transform-preform-operations-on-groups-and-concatenate-the-results.html" class="sidebar-link">Pandas Transform: Preform operations on groups and concatenate the results</a></li><li><a href="/python/similarities-in-syntax-differences-in-meaning-python-vs-javascript.html" class="sidebar-link">Similarities in syntax, Differences in meaning: Python vs. JavaScript</a></li><li><a href="/python/call-python-from-c.html" class="sidebar-link">Call Python from C#</a></li><li><a href="/python/ctypes.html" class="sidebar-link">ctypes</a></li><li><a href="/python/writing-extensions.html" class="sidebar-link">Writing extensions</a></li><li><a href="/python/python-lex-yacc.html" class="sidebar-link">Python Lex-Yacc</a></li><li><a href="/python/unit-testing.html" class="sidebar-link">Unit Testing</a></li><li><a href="/python/py-test.html" class="sidebar-link">py.test</a></li><li><a href="/python/profiling.html" class="sidebar-link">Profiling</a></li><li><a href="/python/python-speed-of-program.html" class="sidebar-link">Python speed of program</a></li><li><a href="/python/performance-optimization.html" class="sidebar-link">Performance optimization</a></li><li><a href="/python/security-and-cryptography.html" class="sidebar-link">Security and Cryptography</a></li><li><a href="/python/secure-shell-connection-in-python.html" class="sidebar-link">Secure Shell Connection in Python</a></li><li><a href="/python/python-anti-patterns.html" class="sidebar-link">Python Anti-Patterns</a></li><li><a href="/python/common-pitfalls.html" class="sidebar-link">Common Pitfalls</a></li><li><a href="/python/hidden-features.html" class="sidebar-link">Hidden Features</a></li><li><a href="/python/date-formatting.html" class="sidebar-link">Date Formatting</a></li><li><a href="/python/ijson.html" class="sidebar-link">ijson</a></li><li><a href="/python/django.html" class="sidebar-link">Django</a></li><li><a href="/python/code-blocks-execution-frames-and-namespaces.html" class="sidebar-link">Code blocks, execution frames, and namespaces</a></li><li><a href="/python/contributors.html" class="sidebar-link">The Contributors</a></li></ul></section></li></ul> </aside> <main class="page"> <div class="theme-default-content content__default"><h1 id="exceptions"><a href="#exceptions" class="header-anchor">#</a> Exceptions</h1> <p>Errors detected during execution are called exceptions and are not unconditionally fatal. Most exceptions are not handled by programs; it is possible to write programs that handle selected exceptions. There are specific features in Python to deal with exceptions and exception logic. Furthermore, exceptions have a rich type hierarchy, all inheriting from the <code>BaseException</code> type.</p> <h2 id="do-not-catch-everything"><a href="#do-not-catch-everything" class="header-anchor">#</a> Do not catch everything!</h2> <p>While it's often tempting to catch every <code>Exception</code>:</p> <div class="language-py extra-class"><pre class="language-py"><code><span class="token keyword">try</span><span class="token punctuation">:</span>
very_difficult_function<span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token keyword">except</span> Exception<span class="token punctuation">:</span>
<span class="token comment"># log / try to reconnect / exit gratiously</span>
<span class="token keyword">finally</span><span class="token punctuation">:</span>
<span class="token keyword">print</span> <span class="token string">"The END"</span>
<span class="token comment"># it runs no matter what execute.</span>
</code></pre></div><p>Or even everything (that includes <code>BaseException</code> and all its children including <code>Exception</code>):</p> <div class="language-py extra-class"><pre class="language-py"><code><span class="token keyword">try</span><span class="token punctuation">:</span>
even_more_difficult_function<span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token keyword">except</span><span class="token punctuation">:</span>
<span class="token keyword">pass</span> <span class="token comment"># do whatever needed</span>
</code></pre></div><p>In most cases it's bad practice. It might catch more than intended, such as <code>SystemExit</code>, <code>KeyboardInterrupt</code> and <code>MemoryError</code> - each of which should generally be handled differently than usual system or logic errors. It also means there's no clear understanding for what the internal code may do wrong and how to recover properly from that condition. If you're catching every error, you wont know what error occurred or how to fix it.</p> <p>This is more commonly referred to as 'bug masking' and should be avoided. Let your program crash instead of silently failing or even worse, failing at deeper level of execution. (Imagine it's a transactional system)</p> <p>Usually these constructs are used at the very outer level of the program, and will log the details of the error so that the bug can be fixed, or the error can be handled more specifically.</p> <h2 id="re-raising-exceptions"><a href="#re-raising-exceptions" class="header-anchor">#</a> Re-raising exceptions</h2> <p>Sometimes you want to catch an exception just to inspect it, e.g. for logging purposes. After the inspection, you want the exception to continue propagating as it did before.</p> <p>In this case, simply use the <code>raise</code> statement with no parameters.</p> <div class="language-py extra-class"><pre class="language-py"><code><span class="token keyword">try</span><span class="token punctuation">:</span>
<span class="token number">5</span> <span class="token operator">/</span> <span class="token number">0</span>
<span class="token keyword">except</span> ZeroDivisionError<span class="token punctuation">:</span>
<span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">"Got an error"</span><span class="token punctuation">)</span>
<span class="token keyword">raise</span>
</code></pre></div><p>Keep in mind, though, that someone further up in the caller stack can still catch the exception and handle it somehow. The done output could be a nuisance in this case because it will happen in any case (caught or not caught).
So it might be a better idea to raise a different exception, containing your comment about the situation as well as the original exception:</p> <div class="language-py extra-class"><pre class="language-py"><code><span class="token keyword">try</span><span class="token punctuation">:</span>
<span class="token number">5</span> <span class="token operator">/</span> <span class="token number">0</span>
<span class="token keyword">except</span> ZeroDivisionError <span class="token keyword">as</span> e<span class="token punctuation">:</span>
<span class="token keyword">raise</span> ZeroDivisionError<span class="token punctuation">(</span><span class="token string">"Got an error"</span><span class="token punctuation">,</span> e<span class="token punctuation">)</span>
</code></pre></div><p>But this has the drawback of reducing the exception trace to exactly this <code>raise</code> while the <code>raise</code> without argument retains the original exception trace.</p> <p>In Python 3 you can keep the original stack by using the <code>raise</code>-<code>from</code> syntax:</p> <div class="language- extra-class"><pre class="language-text"><code>
raise ZeroDivisionError("Got an error") from e
</code></pre></div><h2 id="catching-multiple-exceptions"><a href="#catching-multiple-exceptions" class="header-anchor">#</a> Catching multiple exceptions</h2> <p>There are a few ways to <a href="https://docs.python.org/3/tutorial/errors.html#handling-exceptions" target="_blank" rel="noopener noreferrer">catch multiple exceptions<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a>.</p> <p>The first is by creating a tuple of the exception types you wish to catch and handle in the same manner. This example will cause the code to ignore <code>KeyError</code> and <code>AttributeError</code> exceptions.</p> <div class="language-py extra-class"><pre class="language-py"><code><span class="token keyword">try</span><span class="token punctuation">:</span>
d <span class="token operator">=</span> <span class="token punctuation">{</span><span class="token punctuation">}</span>
a <span class="token operator">=</span> d<span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">]</span>
b <span class="token operator">=</span> d<span class="token punctuation">.</span>non_existing_field
<span class="token keyword">except</span> <span class="token punctuation">(</span>KeyError<span class="token punctuation">,</span> AttributeError<span class="token punctuation">)</span> <span class="token keyword">as</span> e<span class="token punctuation">:</span>
<span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">"A KeyError or an AttributeError exception has been caught."</span><span class="token punctuation">)</span>
</code></pre></div><p>If you wish to handle different exceptions in different ways, you can provide a separate exception block for each type. In this example, we still catch the <code>KeyError</code> and <code>AttributeError</code>, but handle the exceptions in different manners.</p> <div class="language-py extra-class"><pre class="language-py"><code><span class="token keyword">try</span><span class="token punctuation">:</span>
d <span class="token operator">=</span> <span class="token punctuation">{</span><span class="token punctuation">}</span>
a <span class="token operator">=</span> d<span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">]</span>
b <span class="token operator">=</span> d<span class="token punctuation">.</span>non_existing_field
<span class="token keyword">except</span> KeyError <span class="token keyword">as</span> e<span class="token punctuation">:</span>
<span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">"A KeyError has occurred. Exception message:"</span><span class="token punctuation">,</span> e<span class="token punctuation">)</span>
<span class="token keyword">except</span> AttributeError <span class="token keyword">as</span> e<span class="token punctuation">:</span>
<span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">"An AttributeError has occurred. Exception message:"</span><span class="token punctuation">,</span> e<span class="token punctuation">)</span>
</code></pre></div><h2 id="catching-exceptions"><a href="#catching-exceptions" class="header-anchor">#</a> Catching Exceptions</h2> <p>Use <code>try...except:</code> to catch exceptions. You should specify as precise an exception as you can:</p> <div class="language-py extra-class"><pre class="language-py"><code><span class="token keyword">try</span><span class="token punctuation">:</span>
x <span class="token operator">=</span> <span class="token number">5</span> <span class="token operator">/</span> <span class="token number">0</span>
<span class="token keyword">except</span> ZeroDivisionError <span class="token keyword">as</span> e<span class="token punctuation">:</span>
<span class="token comment"># `e` is the exception object</span>
<span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">"Got a divide by zero! The exception was:"</span><span class="token punctuation">,</span> e<span class="token punctuation">)</span>
<span class="token comment"># handle exceptional case</span>
x <span class="token operator">=</span> <span class="token number">0</span>
<span class="token keyword">finally</span><span class="token punctuation">:</span>
<span class="token keyword">print</span> <span class="token string">"The END"</span>
<span class="token comment"># it runs no matter what execute.</span>
</code></pre></div><p>The exception class that is specified - in this case, <code>ZeroDivisionError</code> - catches any exception that is of that class or of any subclass of that exception.</p> <p>For example, <code>ZeroDivisionError</code> is a subclass of <code>ArithmeticError</code>:</p> <div class="language-py extra-class"><pre class="language-py"><code><span class="token operator">>></span><span class="token operator">></span> ZeroDivisionError<span class="token punctuation">.</span>__bases__
<span class="token punctuation">(</span><span class="token operator"><</span><span class="token keyword">class</span> <span class="token string">'ArithmeticError'</span><span class="token operator">></span><span class="token punctuation">,</span><span class="token punctuation">)</span>
</code></pre></div><p>And so, the following will still catch the <code>ZeroDivisionError</code>:</p> <div class="language-py extra-class"><pre class="language-py"><code><span class="token keyword">try</span><span class="token punctuation">:</span>
<span class="token number">5</span> <span class="token operator">/</span> <span class="token number">0</span>
<span class="token keyword">except</span> ArithmeticError<span class="token punctuation">:</span>
<span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">"Got arithmetic error"</span><span class="token punctuation">)</span>
</code></pre></div><h2 id="exception-hierarchy"><a href="#exception-hierarchy" class="header-anchor">#</a> Exception Hierarchy</h2> <p>Exception handling occurs based on an exception hierarchy, determined by the inheritance structure of the exception classes.</p> <p>For example, <code>IOError</code> and <code>OSError</code> are both subclasses of <code>EnvironmentError</code>. Code that catches an <code>IOError</code> will not catch an <code>OSError</code>. However, code that catches an <code>EnvironmentError</code> will catch both <code>IOError</code>s and <code>OSError</code>s.</p> <p>The hierarchy of built-in exceptions:</p> <div class="language-py extra-class"><pre class="language-py"><code>BaseException
<span class="token operator">+</span><span class="token operator">-</span><span class="token operator">-</span> SystemExit
<span class="token operator">+</span><span class="token operator">-</span><span class="token operator">-</span> KeyboardInterrupt
<span class="token operator">+</span><span class="token operator">-</span><span class="token operator">-</span> GeneratorExit
<span class="token operator">+</span><span class="token operator">-</span><span class="token operator">-</span> Exception
<span class="token operator">+</span><span class="token operator">-</span><span class="token operator">-</span> StopIteration
<span class="token operator">+</span><span class="token operator">-</span><span class="token operator">-</span> StandardError
<span class="token operator">|</span> <span class="token operator">+</span><span class="token operator">-</span><span class="token operator">-</span> BufferError
<span class="token operator">|</span> <span class="token operator">+</span><span class="token operator">-</span><span class="token operator">-</span> ArithmeticError
<span class="token operator">|</span> <span class="token operator">|</span> <span class="token operator">+</span><span class="token operator">-</span><span class="token operator">-</span> FloatingPointError
<span class="token operator">|</span> <span class="token operator">|</span> <span class="token operator">+</span><span class="token operator">-</span><span class="token operator">-</span> OverflowError
<span class="token operator">|</span> <span class="token operator">|</span> <span class="token operator">+</span><span class="token operator">-</span><span class="token operator">-</span> ZeroDivisionError
<span class="token operator">|</span> <span class="token operator">+</span><span class="token operator">-</span><span class="token operator">-</span> AssertionError
<span class="token operator">|</span> <span class="token operator">+</span><span class="token operator">-</span><span class="token operator">-</span> AttributeError
<span class="token operator">|</span> <span class="token operator">+</span><span class="token operator">-</span><span class="token operator">-</span> EnvironmentError
<span class="token operator">|</span> <span class="token operator">|</span> <span class="token operator">+</span><span class="token operator">-</span><span class="token operator">-</span> IOError
<span class="token operator">|</span> <span class="token operator">|</span> <span class="token operator">+</span><span class="token operator">-</span><span class="token operator">-</span> OSError
<span class="token operator">|</span> <span class="token operator">|</span> <span class="token operator">+</span><span class="token operator">-</span><span class="token operator">-</span> WindowsError <span class="token punctuation">(</span>Windows<span class="token punctuation">)</span>
<span class="token operator">|</span> <span class="token operator">|</span> <span class="token operator">+</span><span class="token operator">-</span><span class="token operator">-</span> VMSError <span class="token punctuation">(</span>VMS<span class="token punctuation">)</span>
<span class="token operator">|</span> <span class="token operator">+</span><span class="token operator">-</span><span class="token operator">-</span> EOFError
<span class="token operator">|</span> <span class="token operator">+</span><span class="token operator">-</span><span class="token operator">-</span> ImportError
<span class="token operator">|</span> <span class="token operator">+</span><span class="token operator">-</span><span class="token operator">-</span> LookupError
<span class="token operator">|</span> <span class="token operator">|</span> <span class="token operator">+</span><span class="token operator">-</span><span class="token operator">-</span> IndexError
<span class="token operator">|</span> <span class="token operator">|</span> <span class="token operator">+</span><span class="token operator">-</span><span class="token operator">-</span> KeyError
<span class="token operator">|</span> <span class="token operator">+</span><span class="token operator">-</span><span class="token operator">-</span> MemoryError
<span class="token operator">|</span> <span class="token operator">+</span><span class="token operator">-</span><span class="token operator">-</span> NameError
<span class="token operator">|</span> <span class="token operator">|</span> <span class="token operator">+</span><span class="token operator">-</span><span class="token operator">-</span> UnboundLocalError
<span class="token operator">|</span> <span class="token operator">+</span><span class="token operator">-</span><span class="token operator">-</span> ReferenceError
<span class="token operator">|</span> <span class="token operator">+</span><span class="token operator">-</span><span class="token operator">-</span> RuntimeError
<span class="token operator">|</span> <span class="token operator">|</span> <span class="token operator">+</span><span class="token operator">-</span><span class="token operator">-</span> NotImplementedError
<span class="token operator">|</span> <span class="token operator">+</span><span class="token operator">-</span><span class="token operator">-</span> SyntaxError
<span class="token operator">|</span> <span class="token operator">|</span> <span class="token operator">+</span><span class="token operator">-</span><span class="token operator">-</span> IndentationError
<span class="token operator">|</span> <span class="token operator">|</span> <span class="token operator">+</span><span class="token operator">-</span><span class="token operator">-</span> TabError
<span class="token operator">|</span> <span class="token operator">+</span><span class="token operator">-</span><span class="token operator">-</span> SystemError
<span class="token operator">|</span> <span class="token operator">+</span><span class="token operator">-</span><span class="token operator">-</span> TypeError
<span class="token operator">|</span> <span class="token operator">+</span><span class="token operator">-</span><span class="token operator">-</span> ValueError
<span class="token operator">|</span> <span class="token operator">+</span><span class="token operator">-</span><span class="token operator">-</span> UnicodeError
<span class="token operator">|</span> <span class="token operator">+</span><span class="token operator">-</span><span class="token operator">-</span> UnicodeDecodeError
<span class="token operator">|</span> <span class="token operator">+</span><span class="token operator">-</span><span class="token operator">-</span> UnicodeEncodeError
<span class="token operator">|</span> <span class="token operator">+</span><span class="token operator">-</span><span class="token operator">-</span> UnicodeTranslateError
<span class="token operator">+</span><span class="token operator">-</span><span class="token operator">-</span> Warning
<span class="token operator">+</span><span class="token operator">-</span><span class="token operator">-</span> DeprecationWarning
<span class="token operator">+</span><span class="token operator">-</span><span class="token operator">-</span> PendingDeprecationWarning
<span class="token operator">+</span><span class="token operator">-</span><span class="token operator">-</span> RuntimeWarning
<span class="token operator">+</span><span class="token operator">-</span><span class="token operator">-</span> SyntaxWarning
<span class="token operator">+</span><span class="token operator">-</span><span class="token operator">-</span> UserWarning
<span class="token operator">+</span><span class="token operator">-</span><span class="token operator">-</span> FutureWarning
<span class="token operator">+</span><span class="token operator">-</span><span class="token operator">-</span> ImportWarning
<span class="token operator">+</span><span class="token operator">-</span><span class="token operator">-</span> UnicodeWarning
<span class="token operator">+</span><span class="token operator">-</span><span class="token operator">-</span> BytesWarning
</code></pre></div><div class="language-py extra-class"><pre class="language-py"><code>BaseException
<span class="token operator">+</span><span class="token operator">-</span><span class="token operator">-</span> SystemExit
<span class="token operator">+</span><span class="token operator">-</span><span class="token operator">-</span> KeyboardInterrupt
<span class="token operator">+</span><span class="token operator">-</span><span class="token operator">-</span> GeneratorExit
<span class="token operator">+</span><span class="token operator">-</span><span class="token operator">-</span> Exception
<span class="token operator">+</span><span class="token operator">-</span><span class="token operator">-</span> StopIteration
<span class="token operator">+</span><span class="token operator">-</span><span class="token operator">-</span> StopAsyncIteration
<span class="token operator">+</span><span class="token operator">-</span><span class="token operator">-</span> ArithmeticError
<span class="token operator">|</span> <span class="token operator">+</span><span class="token operator">-</span><span class="token operator">-</span> FloatingPointError
<span class="token operator">|</span> <span class="token operator">+</span><span class="token operator">-</span><span class="token operator">-</span> OverflowError
<span class="token operator">|</span> <span class="token operator">+</span><span class="token operator">-</span><span class="token operator">-</span> ZeroDivisionError
<span class="token operator">+</span><span class="token operator">-</span><span class="token operator">-</span> AssertionError
<span class="token operator">+</span><span class="token operator">-</span><span class="token operator">-</span> AttributeError
<span class="token operator">+</span><span class="token operator">-</span><span class="token operator">-</span> BufferError
<span class="token operator">+</span><span class="token operator">-</span><span class="token operator">-</span> EOFError
<span class="token operator">+</span><span class="token operator">-</span><span class="token operator">-</span> ImportError
<span class="token operator">+</span><span class="token operator">-</span><span class="token operator">-</span> LookupError
<span class="token operator">|</span> <span class="token operator">+</span><span class="token operator">-</span><span class="token operator">-</span> IndexError
<span class="token operator">|</span> <span class="token operator">+</span><span class="token operator">-</span><span class="token operator">-</span> KeyError
<span class="token operator">+</span><span class="token operator">-</span><span class="token operator">-</span> MemoryError
<span class="token operator">+</span><span class="token operator">-</span><span class="token operator">-</span> NameError
<span class="token operator">|</span> <span class="token operator">+</span><span class="token operator">-</span><span class="token operator">-</span> UnboundLocalError
<span class="token operator">+</span><span class="token operator">-</span><span class="token operator">-</span> OSError
<span class="token operator">|</span> <span class="token operator">+</span><span class="token operator">-</span><span class="token operator">-</span> BlockingIOError
<span class="token operator">|</span> <span class="token operator">+</span><span class="token operator">-</span><span class="token operator">-</span> ChildProcessError
<span class="token operator">|</span> <span class="token operator">+</span><span class="token operator">-</span><span class="token operator">-</span> ConnectionError
<span class="token operator">|</span> <span class="token operator">|</span> <span class="token operator">+</span><span class="token operator">-</span><span class="token operator">-</span> BrokenPipeError
<span class="token operator">|</span> <span class="token operator">|</span> <span class="token operator">+</span><span class="token operator">-</span><span class="token operator">-</span> ConnectionAbortedError
<span class="token operator">|</span> <span class="token operator">|</span> <span class="token operator">+</span><span class="token operator">-</span><span class="token operator">-</span> ConnectionRefusedError
<span class="token operator">|</span> <span class="token operator">|</span> <span class="token operator">+</span><span class="token operator">-</span><span class="token operator">-</span> ConnectionResetError
<span class="token operator">|</span> <span class="token operator">+</span><span class="token operator">-</span><span class="token operator">-</span> FileExistsError
<span class="token operator">|</span> <span class="token operator">+</span><span class="token operator">-</span><span class="token operator">-</span> FileNotFoundError
<span class="token operator">|</span> <span class="token operator">+</span><span class="token operator">-</span><span class="token operator">-</span> InterruptedError
<span class="token operator">|</span> <span class="token operator">+</span><span class="token operator">-</span><span class="token operator">-</span> IsADirectoryError
<span class="token operator">|</span> <span class="token operator">+</span><span class="token operator">-</span><span class="token operator">-</span> NotADirectoryError
<span class="token operator">|</span> <span class="token operator">+</span><span class="token operator">-</span><span class="token operator">-</span> PermissionError
<span class="token operator">|</span> <span class="token operator">+</span><span class="token operator">-</span><span class="token operator">-</span> ProcessLookupError
<span class="token operator">|</span> <span class="token operator">+</span><span class="token operator">-</span><span class="token operator">-</span> TimeoutError
<span class="token operator">+</span><span class="token operator">-</span><span class="token operator">-</span> ReferenceError
<span class="token operator">+</span><span class="token operator">-</span><span class="token operator">-</span> RuntimeError
<span class="token operator">|</span> <span class="token operator">+</span><span class="token operator">-</span><span class="token operator">-</span> NotImplementedError
<span class="token operator">|</span> <span class="token operator">+</span><span class="token operator">-</span><span class="token operator">-</span> RecursionError
<span class="token operator">+</span><span class="token operator">-</span><span class="token operator">-</span> SyntaxError
<span class="token operator">|</span> <span class="token operator">+</span><span class="token operator">-</span><span class="token operator">-</span> IndentationError
<span class="token operator">|</span> <span class="token operator">+</span><span class="token operator">-</span><span class="token operator">-</span> TabError
<span class="token operator">+</span><span class="token operator">-</span><span class="token operator">-</span> SystemError
<span class="token operator">+</span><span class="token operator">-</span><span class="token operator">-</span> TypeError
<span class="token operator">+</span><span class="token operator">-</span><span class="token operator">-</span> ValueError
<span class="token operator">|</span> <span class="token operator">+</span><span class="token operator">-</span><span class="token operator">-</span> UnicodeError
<span class="token operator">|</span> <span class="token operator">+</span><span class="token operator">-</span><span class="token operator">-</span> UnicodeDecodeError
<span class="token operator">|</span> <span class="token operator">+</span><span class="token operator">-</span><span class="token operator">-</span> UnicodeEncodeError
<span class="token operator">|</span> <span class="token operator">+</span><span class="token operator">-</span><span class="token operator">-</span> UnicodeTranslateError
<span class="token operator">+</span><span class="token operator">-</span><span class="token operator">-</span> Warning
<span class="token operator">+</span><span class="token operator">-</span><span class="token operator">-</span> DeprecationWarning
<span class="token operator">+</span><span class="token operator">-</span><span class="token operator">-</span> PendingDeprecationWarning
<span class="token operator">+</span><span class="token operator">-</span><span class="token operator">-</span> RuntimeWarning
<span class="token operator">+</span><span class="token operator">-</span><span class="token operator">-</span> SyntaxWarning
<span class="token operator">+</span><span class="token operator">-</span><span class="token operator">-</span> UserWarning
<span class="token operator">+</span><span class="token operator">-</span><span class="token operator">-</span> FutureWarning
<span class="token operator">+</span><span class="token operator">-</span><span class="token operator">-</span> ImportWarning
<span class="token operator">+</span><span class="token operator">-</span><span class="token operator">-</span> UnicodeWarning
<span class="token operator">+</span><span class="token operator">-</span><span class="token operator">-</span> BytesWarning
<span class="token operator">+</span><span class="token operator">-</span><span class="token operator">-</span> ResourceWarning
</code></pre></div><h2 id="else"><a href="#else" class="header-anchor">#</a> Else</h2> <p>Code in an else block will only be run if no exceptions were raised by the code in the <code>try</code> block. This is useful if you have some code you don’t want to run if an exception is thrown, but you don’t want exceptions thrown by that code to be caught.</p> <p>For example:</p> <div class="language-py extra-class"><pre class="language-py"><code><span class="token keyword">try</span><span class="token punctuation">:</span>
data <span class="token operator">=</span> <span class="token punctuation">{</span><span class="token number">1</span><span class="token punctuation">:</span> <span class="token string">'one'</span><span class="token punctuation">,</span> <span class="token number">2</span><span class="token punctuation">:</span> <span class="token string">'two'</span><span class="token punctuation">}</span>
<span class="token keyword">print</span><span class="token punctuation">(</span>data<span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">]</span><span class="token punctuation">)</span>
<span class="token keyword">except</span> KeyError <span class="token keyword">as</span> e<span class="token punctuation">:</span>
<span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">'key not found'</span><span class="token punctuation">)</span>
<span class="token keyword">else</span><span class="token punctuation">:</span>
<span class="token keyword">raise</span> ValueError<span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token comment"># Output: one</span>
<span class="token comment"># Output: ValueError</span>
</code></pre></div><p>Note that this kind of <code>else:</code> cannot be combined with an <code>if</code> starting the else-clause to an <code>elif</code>. If you have a following <code>if</code> it needs to stay indented below that <code>else:</code>:</p> <div class="language-py extra-class"><pre class="language-py"><code><span class="token keyword">try</span><span class="token punctuation">:</span>
<span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span>
<span class="token keyword">except</span> <span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">:</span>
<span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span>
<span class="token keyword">else</span><span class="token punctuation">:</span>
<span class="token keyword">if</span> <span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">:</span>
<span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span>
<span class="token keyword">elif</span> <span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">:</span>
<span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span>
<span class="token keyword">else</span><span class="token punctuation">:</span>
<span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span>
</code></pre></div><h2 id="raising-exceptions"><a href="#raising-exceptions" class="header-anchor">#</a> Raising Exceptions</h2> <p>If your code encounters a condition it doesn't know how to handle, such as an incorrect parameter, it should raise the appropriate exception.</p> <div class="language-py extra-class"><pre class="language-py"><code><span class="token keyword">def</span> <span class="token function">even_the_odds</span><span class="token punctuation">(</span>odds<span class="token punctuation">)</span><span class="token punctuation">:</span>
<span class="token keyword">if</span> odds <span class="token operator">%</span> <span class="token number">2</span> <span class="token operator">!=</span> <span class="token number">1</span><span class="token punctuation">:</span>
<span class="token keyword">raise</span> ValueError<span class="token punctuation">(</span><span class="token string">"Did not get an odd number"</span><span class="token punctuation">)</span>
<span class="token keyword">return</span> odds <span class="token operator">+</span> <span class="token number">1</span>
</code></pre></div><h2 id="creating-custom-exception-types"><a href="#creating-custom-exception-types" class="header-anchor">#</a> Creating custom exception types</h2> <p>Create a class inheriting from <code>Exception</code>:</p> <div class="language-py extra-class"><pre class="language-py"><code><span class="token keyword">class</span> <span class="token class-name">FooException</span><span class="token punctuation">(</span>Exception<span class="token punctuation">)</span><span class="token punctuation">:</span>
<span class="token keyword">pass</span>
<span class="token keyword">try</span><span class="token punctuation">:</span>
<span class="token keyword">raise</span> FooException<span class="token punctuation">(</span><span class="token string">"insert description here"</span><span class="token punctuation">)</span>
<span class="token keyword">except</span> FooException<span class="token punctuation">:</span>
<span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">"A FooException was raised."</span><span class="token punctuation">)</span>
</code></pre></div><p>or another exception type:</p> <div class="language-py extra-class"><pre class="language-py"><code><span class="token keyword">class</span> <span class="token class-name">NegativeError</span><span class="token punctuation">(</span>ValueError<span class="token punctuation">)</span><span class="token punctuation">:</span>
<span class="token keyword">pass</span>
<span class="token keyword">def</span> <span class="token function">foo</span><span class="token punctuation">(</span>x<span class="token punctuation">)</span><span class="token punctuation">:</span>
<span class="token comment"># function that only accepts positive values of x</span>
<span class="token keyword">if</span> x <span class="token operator"><</span> <span class="token number">0</span><span class="token punctuation">:</span>
<span class="token keyword">raise</span> NegativeError<span class="token punctuation">(</span><span class="token string">"Cannot process negative numbers"</span><span class="token punctuation">)</span>
<span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span> <span class="token comment"># rest of function body</span>
<span class="token keyword">try</span><span class="token punctuation">:</span>
result <span class="token operator">=</span> foo<span class="token punctuation">(</span><span class="token builtin">int</span><span class="token punctuation">(</span><span class="token builtin">input</span><span class="token punctuation">(</span><span class="token string">"Enter a positive integer: "</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token comment"># raw_input in Python 2.x</span>
<span class="token keyword">except</span> NegativeError<span class="token punctuation">:</span>
<span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">"You entered a negative number!"</span><span class="token punctuation">)</span>
<span class="token keyword">else</span><span class="token punctuation">:</span>
<span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">"The result was "</span> <span class="token operator">+</span> <span class="token builtin">str</span><span class="token punctuation">(</span>result<span class="token punctuation">)</span><span class="token punctuation">)</span>
</code></pre></div><h2 id="exceptions-are-objects-too"><a href="#exceptions-are-objects-too" class="header-anchor">#</a> Exceptions are Objects too</h2> <p>Exceptions are just regular Python objects that inherit from the built-in <code>BaseException</code>. A Python script can use the <code>raise</code> statement to interrupt execution, causing Python to print a stack trace of the call stack at that point and a representation of the exception instance. For example:</p> <div class="language-py extra-class"><pre class="language-py"><code><span class="token operator">>></span><span class="token operator">></span> <span class="token keyword">def</span> <span class="token function">failing_function</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
<span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span> <span class="token keyword">raise</span> ValueError<span class="token punctuation">(</span><span class="token string">'Example error!'</span><span class="token punctuation">)</span>
<span class="token operator">>></span><span class="token operator">></span> failing_function<span class="token punctuation">(</span><span class="token punctuation">)</span>
Traceback <span class="token punctuation">(</span>most recent call last<span class="token punctuation">)</span><span class="token punctuation">:</span>
File <span class="token string">"<stdin>"</span><span class="token punctuation">,</span> line <span class="token number">1</span><span class="token punctuation">,</span> <span class="token keyword">in</span> <span class="token operator"><</span>module<span class="token operator">></span>
File <span class="token string">"<stdin>"</span><span class="token punctuation">,</span> line <span class="token number">2</span><span class="token punctuation">,</span> <span class="token keyword">in</span> failing_function
ValueError<span class="token punctuation">:</span> Example error!
</code></pre></div><p>which says that a <code>ValueError</code> with the message <code>'Example error!'</code> was raised by our <code>failing_function()</code>, which was executed in the interpreter.</p> <p>Calling code can choose to handle any and all types of exception that a call can raise:</p> <div class="language-py extra-class"><pre class="language-py"><code><span class="token operator">>></span><span class="token operator">></span> <span class="token keyword">try</span><span class="token punctuation">:</span>
<span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span> failing_function<span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span> <span class="token keyword">except</span> ValueError<span class="token punctuation">:</span>
<span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span> <span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">'Handled the error'</span><span class="token punctuation">)</span>
Handled the error
</code></pre></div><p>You can get hold of the exception objects by assigning them in the <code>except...</code> part of the exception handling code:</p> <div class="language-py extra-class"><pre class="language-py"><code><span class="token operator">>></span><span class="token operator">></span> <span class="token keyword">try</span><span class="token punctuation">:</span>
<span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span> failing_function<span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span> <span class="token keyword">except</span> ValueError <span class="token keyword">as</span> e<span class="token punctuation">:</span>
<span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span> <span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">'Caught exception'</span><span class="token punctuation">,</span> <span class="token builtin">repr</span><span class="token punctuation">(</span>e<span class="token punctuation">)</span><span class="token punctuation">)</span>
Caught exception ValueError<span class="token punctuation">(</span><span class="token string">'Example error!'</span><span class="token punctuation">,</span><span class="token punctuation">)</span>
</code></pre></div><p>A complete list of built-in Python exceptions along with their descriptions can be found in the Python Documentation: <a href="https://docs.python.org/3.5/library/exceptions.html" target="_blank" rel="noopener noreferrer">https://docs.python.org/3.5/library/exceptions.html<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a>. And here is the full list arranged hierarchically: <a href="http://stackoverflow.com/documentation/python/1788/exceptions/5535/exception-hierarchy" target="_blank" rel="noopener noreferrer">Exception Hierarchy<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a>.</p> <h2 id="practical-examples-of-exception-handling"><a href="#practical-examples-of-exception-handling" class="header-anchor">#</a> Practical examples of exception handling</h2> <h3 id="user-input"><a href="#user-input" class="header-anchor">#</a> User input</h3> <p>Imagine you want a user to enter a number via <code>input</code>. You want to ensure that the input is a number. You can use <code>try</code>/<code>except</code> for this:</p> <div class="language-py extra-class"><pre class="language-py"><code><span class="token keyword">while</span> <span class="token boolean">True</span><span class="token punctuation">:</span>
<span class="token keyword">try</span><span class="token punctuation">:</span>
nb <span class="token operator">=</span> <span class="token builtin">int</span><span class="token punctuation">(</span><span class="token builtin">input</span><span class="token punctuation">(</span><span class="token string">'Enter a number: '</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
<span class="token keyword">break</span>
<span class="token keyword">except</span> ValueError<span class="token punctuation">:</span>
<span class="token keyword">print</span><span class="token punctuation">(</span><span class="token string">'This is not a number, try again.'</span><span class="token punctuation">)</span>
</code></pre></div><p>Note: Python 2.x would use <code>raw_input</code> instead; the function <code>input</code> exists in Python 2.x but has different semantics. In the above example, <code>input</code> would also accept expressions such as <code>2 + 2</code> which evaluate to a number.</p> <p>If the input could not be converted to an integer, a <code>ValueError</code> is raised. You can catch it with <code>except</code>. If no exception is raised, <code>break</code> jumps out of the loop. After the loop, <code>nb</code> contains an integer.</p> <h3 id="dictionaries"><a href="#dictionaries" class="header-anchor">#</a> Dictionaries</h3> <p>Imagine you are iterating over a list of consecutive integers, like <code>range(n)</code>, and you have a list of dictionaries <code>d</code> that contains information about things to do when you encounter some particular integers, say <strong>skip the <code>d[i]</code> next ones</strong>.</p> <div class="language-py extra-class"><pre class="language-py"><code>d <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token punctuation">{</span><span class="token number">7</span><span class="token punctuation">:</span> <span class="token number">3</span><span class="token punctuation">}</span><span class="token punctuation">,</span> <span class="token punctuation">{</span><span class="token number">25</span><span class="token punctuation">:</span> <span class="token number">9</span><span class="token punctuation">}</span><span class="token punctuation">,</span> <span class="token punctuation">{</span><span class="token number">38</span><span class="token punctuation">:</span> <span class="token number">5</span><span class="token punctuation">}</span><span class="token punctuation">]</span>
<span class="token keyword">for</span> i <span class="token keyword">in</span> <span class="token builtin">range</span><span class="token punctuation">(</span><span class="token builtin">len</span><span class="token punctuation">(</span>d<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">:</span>
do_stuff<span class="token punctuation">(</span>i<span class="token punctuation">)</span>
<span class="token keyword">try</span><span class="token punctuation">:</span>
dic <span class="token operator">=</span> d<span class="token punctuation">[</span>i<span class="token punctuation">]</span>
i <span class="token operator">+=</span> dic<span class="token punctuation">[</span>i<span class="token punctuation">]</span>
<span class="token keyword">except</span> KeyError<span class="token punctuation">:</span>
i <span class="token operator">+=</span> <span class="token number">1</span>
</code></pre></div><p>A <code>KeyError</code> will be raised when you try to get a value from a dictionary for a key that doesn’t exist.</p> <h2 id="running-clean-up-code-with-finally"><a href="#running-clean-up-code-with-finally" class="header-anchor">#</a> Running clean-up code with finally</h2> <p>Sometimes, you may want something to occur regardless of whatever exception happened, for example, if you have to clean up some resources.</p> <p>The <code>finally</code> block of a <code>try</code> clause will happen regardless of whether any exceptions were raised.</p> <div class="language-py extra-class"><pre class="language-py"><code>resource <span class="token operator">=</span> allocate_some_expensive_resource<span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token keyword">try</span><span class="token punctuation">:</span>
do_stuff<span class="token punctuation">(</span>resource<span class="token punctuation">)</span>
<span class="token keyword">except</span> SomeException <span class="token keyword">as</span> e<span class="token punctuation">:</span>
log_error<span class="token punctuation">(</span>e<span class="token punctuation">)</span>
<span class="token keyword">raise</span> <span class="token comment"># re-raise the error</span>
<span class="token keyword">finally</span><span class="token punctuation">:</span>
free_expensive_resource<span class="token punctuation">(</span>resource<span class="token punctuation">)</span>
</code></pre></div><p>This pattern is often better handled with context managers (using <a href="http://stackoverflow.com/documentation/python/928/context-managers-with-statement" target="_blank" rel="noopener noreferrer">the <code>with</code> statement<span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a>).</p> <h2 id="chain-exceptions-with-raise-from"><a href="#chain-exceptions-with-raise-from" class="header-anchor">#</a> Chain exceptions with raise from</h2> <p>In the process of handling an exception, you may want to raise another exception. For example, if you get an <code>IOError</code> while reading from a file, you may want to raise an application-specific error to present to the users of your library, instead.</p> <p>You can chain exceptions to show how the handling of exceptions proceeded:</p> <div class="language-py extra-class"><pre class="language-py"><code><span class="token operator">>></span><span class="token operator">></span> <span class="token keyword">try</span><span class="token punctuation">:</span>
<span class="token number">5</span> <span class="token operator">/</span> <span class="token number">0</span>
<span class="token keyword">except</span> ZeroDivisionError <span class="token keyword">as</span> e<span class="token punctuation">:</span>
<span class="token keyword">raise</span> ValueError<span class="token punctuation">(</span><span class="token string">"Division failed"</span><span class="token punctuation">)</span> <span class="token keyword">from</span> e
Traceback <span class="token punctuation">(</span>most recent call last<span class="token punctuation">)</span><span class="token punctuation">:</span>
File <span class="token string">"<stdin>"</span><span class="token punctuation">,</span> line <span class="token number">2</span><span class="token punctuation">,</span> <span class="token keyword">in</span> <span class="token operator"><</span>module<span class="token operator">></span>
ZeroDivisionError<span class="token punctuation">:</span> division by zero
The above exception was the direct cause of the following exception<span class="token punctuation">:</span>
Traceback <span class="token punctuation">(</span>most recent call last<span class="token punctuation">)</span><span class="token punctuation">:</span>
File <span class="token string">"<stdin>"</span><span class="token punctuation">,</span> line <span class="token number">4</span><span class="token punctuation">,</span> <span class="token keyword">in</span> <span class="token operator"><</span>module<span class="token operator">></span>
ValueError<span class="token punctuation">:</span> Division failed
</code></pre></div><h4 id="syntax"><a href="#syntax" class="header-anchor">#</a> Syntax</h4> <ul><li>raise <strong>exception</strong></li> <li>raise # re-raise an exception that’s already been raised</li> <li>raise <strong>exception</strong> from <strong>cause</strong> # Python 3 - set exception cause</li> <li>raise <strong>exception</strong> from None # Python 3 - suppress all exception context</li> <li>try:</li> <li>except <strong>[exception types]</strong> <strong>[</strong> as <strong>identifier</strong> <strong>]</strong>:</li> <li>else:</li> <li>finally:</li></ul></div> <footer class="page-edit"><div class="edit-link"><a href="https://github.com/devtut/generate/edit/master/docs/python/exceptions.md" target="_blank" rel="noopener noreferrer">Edit this page on GitHub</a> <span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></div> <!----></footer> <div class="page-nav"><p class="inner"><span class="prev">
←
<a href="/python/type-hints.html" class="prev">
Type Hints
</a></span> <span class="next"><a href="/python/raise-custom-errors-exceptions.html">
Raise Custom Errors / Exceptions
</a>
→
</span></p></div> </main></div><div class="global-ui"><!----></div></div>
<script src="/assets/js/app.1779e102.js" defer></script><script src="/assets/js/3.2cfa8016.js" defer></script><script src="/assets/js/2702.5705e114.js" defer></script>
</body>
</html>