Skip to content

Commit 33e26d0

Browse files
committed
Document the raise_from function for exception chaining (PEP 3134)
1 parent af5325e commit 33e26d0

File tree

1 file changed

+71
-1
lines changed

1 file changed

+71
-1
lines changed

docs/notebooks/Writing Python 2-3 compatible code.ipynb

Lines changed: 71 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
{
22
"metadata": {
33
"name": "",
4-
"signature": "sha256:a318d976dd8aacb67a39acbcafddb513645c61ae27874c0d32d4a64c1621ca35"
4+
"signature": "sha256:f4ac8456d9c7976cb130d88556b7bbe2c3494a960d29e3eeffdca80a91b080e3"
55
},
66
"nbformat": 3,
77
"nbformat_minor": 0,
@@ -294,6 +294,76 @@
294294
"metadata": {},
295295
"outputs": []
296296
},
297+
{
298+
"cell_type": "markdown",
299+
"metadata": {},
300+
"source": [
301+
"Exception chaining (PEP 3134):"
302+
]
303+
},
304+
{
305+
"cell_type": "code",
306+
"collapsed": false,
307+
"input": [
308+
"# Setup:\n",
309+
"class DatabaseError(Exception):\n",
310+
" pass"
311+
],
312+
"language": "python",
313+
"metadata": {},
314+
"outputs": [],
315+
"prompt_number": 3
316+
},
317+
{
318+
"cell_type": "code",
319+
"collapsed": false,
320+
"input": [
321+
"# Python 3 only\n",
322+
"class FileDatabase:\n",
323+
" def __init__(self, filename):\n",
324+
" try:\n",
325+
" self.file = open(filename)\n",
326+
" except IOError as exc:\n",
327+
" raise DatabaseError('failed to open') from exc"
328+
],
329+
"language": "python",
330+
"metadata": {},
331+
"outputs": []
332+
},
333+
{
334+
"cell_type": "code",
335+
"collapsed": false,
336+
"input": [
337+
"# Python 2 and 3:\n",
338+
"from future.utils import raise_from\n",
339+
"\n",
340+
"class FileDatabase:\n",
341+
" def __init__(self, filename):\n",
342+
" try:\n",
343+
" self.file = open(filename)\n",
344+
" except IOError as exc:\n",
345+
" raise_from(DatabaseError('failed to open'), exc)"
346+
],
347+
"language": "python",
348+
"metadata": {},
349+
"outputs": [],
350+
"prompt_number": 16
351+
},
352+
{
353+
"cell_type": "code",
354+
"collapsed": false,
355+
"input": [
356+
"# Testing the above:\n",
357+
"try:\n",
358+
" fd = FileDatabase('non_existent_file.txt')\n",
359+
"except Exception as e:\n",
360+
" assert isinstance(e.__cause__, IOError) # FileNotFoundError on Py3.3+ inherits from IOError"
361+
],
362+
"language": "python",
363+
"metadata": {},
364+
"outputs": [],
365+
"prompt_number": 17
366+
},
297367
{
298368
"cell_type": "heading",
299369
"level": 3,

0 commit comments

Comments
 (0)