Repository navigation
Expand file tree
/
Copy pathexception
More file actions
executable file
·300 lines (263 loc) · 8.93 KB
/
Copy pathexception
File metadata and controls
executable file
·300 lines (263 loc) · 8.93 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
#!/usr/bin/env python
# Demonstrate basic syntax of some exception handling cases
import sys
import os
class foo(Exception): pass
class bar(Exception): pass
try:
raise foo ("help")
except (foo, bar) as e: # Use parens to group multiple exceptions
print(f"Raised {e}, with cause {e.__cause__}")
global exception_ids
exception_ids = []
def reraise():
try:
exc = foo("raised foo")
exception_ids.append(id(exc))
raise exc
except Exception as e:
exc = foo("reraised bar")
exception_ids.append(id(exc))
raise exc from e
finally: # finally clause is executed whether an exception is thrown or not
print('finally in re-raised foo')
# Pre 3.14, break in a finally discards an exception raised in an except clause
# In 3.14+, a break in a finally statement raises SyntaxWarning
# while True:
# try: a = int('foo')
# except ValueError as e: raise e
# finally: break
print('This is reached because break in finally discards the raise in except')
# See https://peps.python.org/pep-0601/
# KeyboardInterrupt is indistinuishable from receiving a SIGINT. Perhaps there
# is some platform on which that is not true.
exception_ids.clear()
try:
reraise()
except Exception as e: # Does not catch SystemExit or KeyboardInterrupt
assert(str(e) == 'reraised bar')
assert(e.args[0] == 'reraised bar')
c = e.__cause__
assert(isinstance(c, foo))
assert(str(c) == 'raised foo')
assert exception_ids == [id(c), id(e)]
except BaseException as e: # *Does* catch SystemExit and KeyboardInterrupt
pass
# Demonstrate pathological behavior of return
def f(flag=False):
try:
print('try')
if flag: raise foo('bar')
return 5
except: # bare exception DO NOT EVER DO THIS
print('except')
else: # normally executes if no exception was raised
print('else')
# However, in this case we "return" in the try, so the else clause is skipped
finally: # Executed after any except/else clause
print('finally')
# If there is an exception before return in try, then
# the function returns None unless the finally clause returns a value.
# If not, it returns 5 and executes the finally clause
# and still returns 5, regardless of whehter or not the finally
# clause returns. Returning something from a finally clause is bad practice
# IMO, it is best practce to avoid return in try as well
rv = f()
print('f without exception returns:', rv)
rv = f(True)
print('f with exception returns:', rv)
try:
print('try/finally with no except'),
finally:
print('is ok')
# Demonstrate getting IO error messages
def open_file(path):
try:
f = open(path, 'r')
except IOError as e:
sys.stderr.write("{}: {}: {}\n".format(
os.path.basename(sys.argv[0]), e.filename, e.strerror))
try: open_file('/non/extant-file')
except Exception: pass
# Last example, since this will abort. Trigger a stacktrace
def func1(a):
func2(a)
def func2(a):
try:
func3(a)
except Exception as e:
if hasattr(e, 'add_note'): # Added in 3.11
e.add_note(f"This note is added to the exception")
raise e
def func3(a):
raise foo('f1->f2->f3')
try:
func1(3)
except Exception as e:
assert(str(e) == 'f1->f2->f3')
assert(e.__notes__ == ['This note is added to the exception'])
"""
List of builtin exceptions, culled from Doc/library/exceptions.rst
Built-in Exceptions
===================
.. exception:: BaseException
.. exception:: Exception
.. exception:: ArithmeticError
.. exception:: BufferError
.. exception:: LookupError
Concrete exceptions
-------------------
.. exception:: AssertionError
.. exception:: AttributeError
.. exception:: EOFError
.. exception:: FloatingPointError # Not currently used.
.. exception:: GeneratorExit
.. exception:: ImportError
.. exception:: ModuleNotFoundError
.. exception:: IndexError
.. exception:: KeyError
.. exception:: KeyboardInterrupt
.. exception:: MemoryError
.. exception:: NameError
.. exception:: NotImplementedError
.. exception:: OSError([arg])
.. exception:: OverflowError
.. exception:: PythonFinalizationError
.. exception:: RecursionError
.. exception:: ReferenceError
.. exception:: RuntimeError
.. exception:: StopIteration
.. exception:: StopAsyncIteration
.. exception:: SyntaxError(message, details)
.. exception:: IndentationError
.. exception:: TabError
.. exception:: SystemError
.. exception:: SystemExit
.. exception:: TypeError
.. exception:: UnboundLocalError
.. exception:: UnicodeError
.. exception:: UnicodeEncodeError
.. exception:: UnicodeDecodeError
.. exception:: UnicodeTranslateError
.. exception:: ValueError
.. exception:: ZeroDivisionError
The following exceptions are kept for compatibility with previous versions;
starting from Python 3.3, they are aliases of :exc:`OSError`.
.. exception:: EnvironmentError
.. exception:: IOError
.. exception:: WindowsError
OS exceptions
^^^^^^^^^^^^^
The following exceptions are subclasses of :exc:`OSError`, they get raised
depending on the system error code.
.. exception:: BlockingIOError
.. exception:: ChildProcessError
.. exception:: ConnectionError
.. exception:: BrokenPipeError
.. exception:: ConnectionAbortedError
.. exception:: ConnectionRefusedError
.. exception:: ConnectionResetError
.. exception:: FileExistsError
.. exception:: FileNotFoundError
.. exception:: InterruptedError
.. exception:: IsADirectoryError
.. exception:: NotADirectoryError
.. exception:: PermissionError
.. exception:: ProcessLookupError
.. exception:: TimeoutError
.. seealso:: :pep:`3151` - Reworking the OS and IO exception hierarchy
Warnings
--------
.. exception:: Warning
.. exception:: UserWarning
.. exception:: DeprecationWarning
.. exception:: PendingDeprecationWarning
.. exception:: SyntaxWarning
.. exception:: RuntimeWarning
.. exception:: FutureWarning
.. exception:: ImportWarning
.. exception:: UnicodeWarning
.. exception:: EncodingWarning
.. exception:: BytesWarning
.. exception:: ResourceWarning
Exception groups
----------------
The following are used when it is necessary to raise multiple unrelated
exceptions. They are part of the exception hierarchy so they can be
handled with :keyword:`except` like all other exceptions. In addition,
they are recognised by :keyword:`except*<except_star>`, which matches
their subgroups based on the types of the contained exceptions.
.. exception:: ExceptionGroup(msg, excs)
.. exception:: BaseExceptionGroup(msg, excs)
Exception hierarchy
-------------------
The class hierarchy for built-in exceptions is in Lib/test/exception_hierarchy.txt
BaseException
├── BaseExceptionGroup
├── GeneratorExit
├── KeyboardInterrupt
├── SystemExit
└── Exception
├── ArithmeticError
│ ├── FloatingPointError
│ ├── OverflowError
│ └── ZeroDivisionError
├── AssertionError
├── AttributeError
├── BufferError
├── EOFError
├── ExceptionGroup [BaseExceptionGroup]
├── ImportError
│ └── ModuleNotFoundError
├── LookupError
│ ├── IndexError
│ └── KeyError
├── MemoryError
├── NameError
│ └── UnboundLocalError
├── OSError
│ ├── BlockingIOError
│ ├── ChildProcessError
│ ├── ConnectionError
│ │ ├── BrokenPipeError
│ │ ├── ConnectionAbortedError
│ │ ├── ConnectionRefusedError
│ │ └── ConnectionResetError
│ ├── FileExistsError
│ ├── FileNotFoundError
│ ├── InterruptedError
│ ├── IsADirectoryError
│ ├── NotADirectoryError
│ ├── PermissionError
│ ├── ProcessLookupError
│ └── TimeoutError
├── ReferenceError
├── RuntimeError
│ ├── NotImplementedError
│ ├── PythonFinalizationError
│ └── RecursionError
├── StopAsyncIteration
├── StopIteration
├── SyntaxError
│ └── IndentationError
│ └── TabError
├── SystemError
├── TypeError
├── ValueError
│ └── UnicodeError
│ ├── UnicodeDecodeError
│ ├── UnicodeEncodeError
│ └── UnicodeTranslateError
└── Warning
├── BytesWarning
├── DeprecationWarning
├── EncodingWarning
├── FutureWarning
├── ImportWarning
├── PendingDeprecationWarning
├── ResourceWarning
├── RuntimeWarning
├── SyntaxWarning
├── UnicodeWarning
└── UserWarning
"""