@@ -147,10 +147,52 @@ For example, the following code will print B, C, D in that order::
147
147
Note that if the *except clauses * were reversed (with ``except B `` first), it
148
148
would have printed B, B, B --- the first matching *except clause * is triggered.
149
149
150
- All exceptions inherit from :exc: `BaseException `, and so it can be used to serve
151
- as a wildcard. Use this with extreme caution, since it is easy to mask a real
152
- programming error in this way! It can also be used to print an error message and
153
- then re-raise the exception (allowing a caller to handle the exception as well)::
150
+ When an exception occurs, it may have associated values, also known as the
151
+ exception's *arguments *. The presence and types of the arguments depend on the
152
+ exception type.
153
+
154
+ The *except clause * may specify a variable after the exception name. The
155
+ variable is bound to the exception instance which typically has an ``args ``
156
+ attribute that stores the arguments. For convenience, builtin exception
157
+ types define :meth: `__str__ ` to print all the arguments without explicitly
158
+ accessing ``.args ``. ::
159
+
160
+ >>> try:
161
+ ... raise Exception('spam', 'eggs')
162
+ ... except Exception as inst:
163
+ ... print(type(inst)) # the exception instance
164
+ ... print(inst.args) # arguments stored in .args
165
+ ... print(inst) # __str__ allows args to be printed directly,
166
+ ... # but may be overridden in exception subclasses
167
+ ... x, y = inst.args # unpack args
168
+ ... print('x =', x)
169
+ ... print('y =', y)
170
+ ...
171
+ <class 'Exception'>
172
+ ('spam', 'eggs')
173
+ ('spam', 'eggs')
174
+ x = spam
175
+ y = eggs
176
+
177
+ The exception's :meth: `__str__ ` output is printed as the last part ('detail')
178
+ of the message for unhandled exceptions.
179
+
180
+ :exc: `BaseException ` is the common base class of all exceptions. One of its
181
+ subclasses, :exc: `Exception `, is the base class of all the non-fatal exceptions.
182
+ Exceptions which are not subclasses of :exc: `Exception ` are not typically
183
+ handled, because they are used to indicate that the program should terminate.
184
+ They include :exc: `SystemExit ` which is raised by :meth: `sys.exit ` and
185
+ :exc: `KeyboardInterrupt ` which is raised when a user wishes to interrupt
186
+ the program.
187
+
188
+ :exc: `Exception ` can be used as a wildcard that catches (almost) everything.
189
+ However, it is good practice to be as specific as possible with the types
190
+ of exceptions that we intend to handle, and to allow any unexpected
191
+ exceptions to propagate on.
192
+
193
+ The most common pattern for handling :exc: `Exception ` is to print or log
194
+ the exception and then re-raise it (allowing a caller to handle the
195
+ exception as well)::
154
196
155
197
import sys
156
198
@@ -159,16 +201,13 @@ then re-raise the exception (allowing a caller to handle the exception as well):
159
201
s = f.readline()
160
202
i = int(s.strip())
161
203
except OSError as err:
162
- print("OS error: {0}".format( err) )
204
+ print("OS error:", err)
163
205
except ValueError:
164
206
print("Could not convert data to an integer.")
165
- except BaseException as err:
207
+ except Exception as err:
166
208
print(f"Unexpected {err=}, {type(err)=}")
167
209
raise
168
210
169
- Alternatively the last except clause may omit the exception name(s), however the exception
170
- value must then be retrieved with ``sys.exception() ``.
171
-
172
211
The :keyword: `try ` ... :keyword: `except ` statement has an optional *else
173
212
clause *, which, when present, must follow all *except clauses *. It is useful
174
213
for code that must be executed if the *try clause * does not raise an exception.
@@ -188,39 +227,8 @@ the :keyword:`try` clause because it avoids accidentally catching an exception
188
227
that wasn't raised by the code being protected by the :keyword: `!try ` ...
189
228
:keyword: `!except ` statement.
190
229
191
- When an exception occurs, it may have an associated value, also known as the
192
- exception's *argument *. The presence and type of the argument depend on the
193
- exception type.
194
-
195
- The *except clause * may specify a variable after the exception name. The
196
- variable is bound to an exception instance with the arguments stored in
197
- ``instance.args ``. For convenience, the exception instance defines
198
- :meth: `__str__ ` so the arguments can be printed directly without having to
199
- reference ``.args ``. One may also instantiate an exception first before
200
- raising it and add any attributes to it as desired. ::
201
-
202
- >>> try:
203
- ... raise Exception('spam', 'eggs')
204
- ... except Exception as inst:
205
- ... print(type(inst)) # the exception instance
206
- ... print(inst.args) # arguments stored in .args
207
- ... print(inst) # __str__ allows args to be printed directly,
208
- ... # but may be overridden in exception subclasses
209
- ... x, y = inst.args # unpack args
210
- ... print('x =', x)
211
- ... print('y =', y)
212
- ...
213
- <class 'Exception'>
214
- ('spam', 'eggs')
215
- ('spam', 'eggs')
216
- x = spam
217
- y = eggs
218
-
219
- If an exception has arguments, they are printed as the last part ('detail') of
220
- the message for unhandled exceptions.
221
-
222
- Exception handlers don't just handle exceptions if they occur immediately in the
223
- *try clause *, but also if they occur inside functions that are called (even
230
+ Exception handlers do not handle only exceptions that occur immediately in the
231
+ *try clause *, but also those that occur inside functions that are called (even
224
232
indirectly) in the *try clause *. For example::
225
233
226
234
>>> def this_fails():
@@ -249,8 +257,9 @@ exception to occur. For example::
249
257
250
258
The sole argument to :keyword: `raise ` indicates the exception to be raised.
251
259
This must be either an exception instance or an exception class (a class that
252
- derives from :class: `Exception `). If an exception class is passed, it will
253
- be implicitly instantiated by calling its constructor with no arguments::
260
+ derives from :class: `BaseException `, such as :exc: `Exception ` or one of its
261
+ subclasses). If an exception class is passed, it will be implicitly
262
+ instantiated by calling its constructor with no arguments::
254
263
255
264
raise ValueError # shorthand for 'raise ValueError()'
256
265
@@ -335,8 +344,7 @@ Most exceptions are defined with names that end in "Error", similar to the
335
344
naming of the standard exceptions.
336
345
337
346
Many standard modules define their own exceptions to report errors that may
338
- occur in functions they define. More information on classes is presented in
339
- chapter :ref: `tut-classes `.
347
+ occur in functions they define.
340
348
341
349
342
350
.. _tut-cleanup :
0 commit comments