Skip to content

파이썬 Exception #

Find similar titles
  • 최초 작성자

Structured data

Category
Programming

Overview #

Python 3 has useful feature such as chaining the exceptions more in improved way rather than Python 2.

Examples #

Situation: we catch an exception with except, do something, and then raise a different exception.

def mycopy(source, dest):
    try:
        shutil.copy2(source, dest)
    except OSError: # We don't have permissions. More on this later
        raise NotImplementedError("automatic sudo injection")

Problem: we lose the original traceback

>>> mycopy('noway', 'noway2')
>>> mycopy(1, 2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 5, in mycopy
NotImplementedError: automatic sudo injection

Python 3 shows us the whole chain of exceptions:

mycopy('noway', 'noway2')
Traceback (most recent call last):
File "<stdin>", line 3, in mycopy
File "/Users/aaronmeurer/anaconda3/lib/python3.3/shutil.py", line 243, in copy2
 copyfile(src, dst, follow_symlinks=follow_symlinks)
File "/Users/aaronmeurer/anaconda3/lib/python3.3/shutil.py", line 109, in copyfile
 with open(src, 'rb') as fsrc:
PermissionError: [Errno 13] Permission denied: 'noway'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 5, in mycopy
NotImplementedError: automatic sudo injection

We can also do this manually using raise

from raise exception from e

>>> raise NotImplementedError from OSError
OSError
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NotImplementedError

References #

  1. https://docs.python.org/3/library/exceptions.html
  2. http://www.asmeurer.com/python3-presentation/python3-presentation.pdf

Suggested Pages #

0.0.1_20230725_7_v68