|
1 | 1 | { |
2 | 2 | "metadata": { |
3 | 3 | "name": "", |
4 | | - "signature": "sha256:a318d976dd8aacb67a39acbcafddb513645c61ae27874c0d32d4a64c1621ca35" |
| 4 | + "signature": "sha256:f4ac8456d9c7976cb130d88556b7bbe2c3494a960d29e3eeffdca80a91b080e3" |
5 | 5 | }, |
6 | 6 | "nbformat": 3, |
7 | 7 | "nbformat_minor": 0, |
|
294 | 294 | "metadata": {}, |
295 | 295 | "outputs": [] |
296 | 296 | }, |
| 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 | + }, |
297 | 367 | { |
298 | 368 | "cell_type": "heading", |
299 | 369 | "level": 3, |
|
0 commit comments