To amplify Messa, catch what you expect are failure modes that you know how to recover from. Ian Bicking wrote an article that addresses some of the overarching principles as does Eli Bendersky's note.

The problem with the sample code is that it is not handling errors, just prettifying them and discarding them. Your code does not "know" what to do with a NameError and there isn't much it should do other than pass it up, look at Bicking's re-raise if you feel you must add detail.

IOError and OSError are reasonably "expectable" for a shutil.move but not necessarily handleable. And the caller of your function wanted it to move a file and may itself break if that "contract" that Eli writes of is broken.

Catch what you can fix, adorn and re-raise what you expect but can't fix, and let the caller deal with what you didn't expect, even if the code that "deals" is seven levels up the stack in main.

Answer from msw on Stack Overflow
๐ŸŒ
Python
docs.python.org โ€บ 3 โ€บ builtins โ€บ exceptions.html
Built-in Exceptions โ€” Python 3.14.7 documentation
In Python, all exceptions must be instances of a class that derives from BaseException. In a try statement with an except clause that mentions a particular class, that clause also handles any exception classes derived from that class (but not exception classes from which it is derived). Two exception classes that are not related via subclassing are never equivalent, even if they have the same name. The built-in exceptions listed ...
๐ŸŒ
W3Schools
w3schools.com โ€บ python โ€บ python_ref_exceptions.asp
Python Built-in Exceptions
The table below shows built-in exceptions that are usually raised in Python.
People also ask

How do you find a logical error in Python?
Logical errors raise nothing, so the interpreter cannot help. Compare the output you got against the output you expected on a small input you can verify by hand, then narrow the gap with print statements, a debugger, or unit tests that assert the expected result. Code review is effective here because the bug is in the reasoning, not the syntax.
๐ŸŒ
last9.io
last9.io โ€บ blog โ€บ types-of-errors-in-python
Types of Errors in Python: Syntax, Runtime, and Logical Explained ...
What is the difference between an error and an exception in Python?
An exception is the object Python raises when something goes wrong at runtime, and your code can catch it with try and except. "Error" is the broader word, and it also covers syntax errors, which cannot be caught this way because the file never runs. In practice most runtime errors are exceptions, which is why the two terms are often used interchangeably.
๐ŸŒ
last9.io
last9.io โ€บ blog โ€บ types-of-errors-in-python
Types of Errors in Python: Syntax, Runtime, and Logical Explained ...
What is the most common error in Python?
For beginners, SyntaxError and IndentationError are the most frequent, since both come from formatting rather than logic. Among runtime exceptions, TypeError, NameError, and KeyError are the ones you meet most often in day-to-day code.
๐ŸŒ
last9.io
last9.io โ€บ blog โ€บ types-of-errors-in-python
Types of Errors in Python: Syntax, Runtime, and Logical Explained ...
Top answer
1 of 4
12

To amplify Messa, catch what you expect are failure modes that you know how to recover from. Ian Bicking wrote an article that addresses some of the overarching principles as does Eli Bendersky's note.

The problem with the sample code is that it is not handling errors, just prettifying them and discarding them. Your code does not "know" what to do with a NameError and there isn't much it should do other than pass it up, look at Bicking's re-raise if you feel you must add detail.

IOError and OSError are reasonably "expectable" for a shutil.move but not necessarily handleable. And the caller of your function wanted it to move a file and may itself break if that "contract" that Eli writes of is broken.

Catch what you can fix, adorn and re-raise what you expect but can't fix, and let the caller deal with what you didn't expect, even if the code that "deals" is seven levels up the stack in main.

2 of 4
5

Python doesn't have a mechanism right now for declaring which exceptions are thrown, unlike (for example) Java. (In Java you have to define exactly which exceptions are thrown by what, and if one of your utility methods needs to throw another exception then you need to add it to all of the methods which call it which gets boring quickly!)

So if you want to discover exactly which exceptions are thrown by any given bit of python then you need to examine the documentation and the source.

However python has a really good exception hierarchy.

If you study the exception hierarchy below you'll see that the error superclass you want to catch is called StandardError - this should catch all the errors that might be generated in normal operations. Turning the error into into a string will give a reasonable idea to the user as to what went wrong, so I'd suggest your code above should look like

from shutil import move
try:
    move('somefile.txt', '/tmp/somefile.txt')
except StandardError, e:
    print 'Move failed: %s' % e

Exception hierarchy

BaseException
|---Exception
|---|---StandardError
|---|---|---ArithmeticError
|---|---|---|---FloatingPointError
|---|---|---|---OverflowError
|---|---|---|---ZeroDivisionError
|---|---|---AssertionError
|---|---|---AttributeError
|---|---|---BufferError
|---|---|---EOFError
|---|---|---EnvironmentError
|---|---|---|---IOError
|---|---|---|---OSError
|---|---|---ImportError
|---|---|---LookupError
|---|---|---|---IndexError
|---|---|---|---KeyError
|---|---|---MemoryError
|---|---|---NameError
|---|---|---|---UnboundLocalError
|---|---|---ReferenceError
|---|---|---RuntimeError
|---|---|---|---NotImplementedError
|---|---|---SyntaxError
|---|---|---|---IndentationError
|---|---|---|---|---TabError
|---|---|---SystemError
|---|---|---TypeError
|---|---|---ValueError
|---|---|---|---UnicodeError
|---|---|---|---|---UnicodeDecodeError
|---|---|---|---|---UnicodeEncodeError
|---|---|---|---|---UnicodeTranslateError
|---|---StopIteration
|---|---Warning
|---|---|---BytesWarning
|---|---|---DeprecationWarning
|---|---|---FutureWarning
|---|---|---ImportWarning
|---|---|---PendingDeprecationWarning
|---|---|---RuntimeWarning
|---|---|---SyntaxWarning
|---|---|---UnicodeWarning
|---|---|---UserWarning
|---GeneratorExit
|---KeyboardInterrupt
|---SystemExit

This also means that when defining your own exceptions you should base them off StandardError not Exception.

Base class for all standard Python exceptions that do not represent
interpreter exiting.
๐ŸŒ
Real Python
realpython.com โ€บ ref โ€บ builtin-exceptions
Pythonโ€™s Built-in Exceptions (Reference) โ€“ Real Python
Python has a structured set of exceptions that cover many error conditions. In your code, you can catch specific errors by name to manage errors more precisely. Below is a list of Pythonโ€™s built-in exceptions and their purposes:
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ built-exceptions-python
Python Built-in Exceptions - GeeksforGeeks
In Python 3: IOError is just an alias for OSError (they are the same). FileNotFoundError is a subclass of OSError, specifically raised when a file or directory does not exist. Example: This example attempts to open a missing file, which triggers FileNotFoundError (a subclass of OSError). ... try: open("non_existent_file.txt") # File does not exist except FileNotFoundError as e: # More specific print("FileNotFoundError caught:", e) except OSError as e: # General OS-related error print("OSError caught:", e)
Published: April 18, 2026
๐ŸŒ
Runestone Academy
runestone.academy โ€บ ns โ€บ books โ€บ published โ€บ fopp โ€บ Exceptions โ€บ standard-exceptions.html
19.4. Standard Exceptions โ€” Foundations of Python Programming
BaseException +-- SystemExit +-- KeyboardInterrupt +-- GeneratorExit +-- Exception +-- StopIteration +-- StopAsyncIteration +-- ArithmeticError | +-- FloatingPointError | +-- OverflowError | +-- ZeroDivisionError +-- AssertionError +-- AttributeError +-- BufferError +-- EOFError +-- ImportError +-- LookupError | +-- IndexError | +-- KeyError +-- MemoryError +-- NameError | +-- UnboundLocalError +-- OSError | +-- BlockingIOError | +-- ChildProcessError | +-- ConnectionError | | +-- BrokenPipeError | | +-- ConnectionAbortedError | | +-- ConnectionRefusedError | | +-- ConnectionResetError | +-- F
Find elsewhere
๐ŸŒ
UTK
web.eecs.utk.edu โ€บ ~bvanderz โ€บ cs365 โ€บ notes โ€บ Python โ€บ PythonExceptionHandling.html
exception handling
try: protected code except ExceptionName1 as e1: error handling code except ExceptionName2 as e2: error handling code except ExceptionName3: error handling code except: unconditional error handling code raise # re-raises the exception else: code to execute if the try completes successfully. This code is non-protected code (i.e., code we do not expect to cause an exception) finally: code executed regardless of whether an exception occurs, and regardless of whether an exception is handled if one occurs Here is an example from the Python tutorial:
๐ŸŒ
Read the Docs
python.readthedocs.io โ€บ fr โ€บ latest โ€บ library โ€บ exceptions.html
5. Built-in Exceptions โ€” documentation Python 3.7.0a0
Modifiรฉ dans la version 3.5: Python now retries system calls when a syscall is interrupted by a signal, except if the signal handler raises an exception (see PEP 475 for the rationale), instead of raising InterruptedError. ... Raised when a file operation (such as os.remove()) is requested on a directory. Corresponds to errno EISDIR. ... Raised when a directory operation (such as os.listdir()) is requested on something which is not a directory.
๐ŸŒ
Python
python.org โ€บ doc โ€บ essays โ€บ stdexceptions
Standard Exception Classes in Python 1.5 | Python.org
[a, b, c] = x requires that x is a list with three items. As part of the same project, the right hand side of either statement can be any sequence with exactly three items. This makes it possible to extract e.g. the errno and strerror values from an IOError exception in a backwards compatible way:
๐ŸŒ
Last9
last9.io โ€บ blog โ€บ types-of-errors-in-python
Types of Errors in Python: Syntax, Runtime, and Logical Explained | Last9
January 3, 2025 - A logical error lets it run to the end and returns the wrong answer. Every named exception you meet, TypeError, KeyError, NameError, and the rest, is a specific case of one of these three.
๐ŸŒ
Medium
medium.com โ€บ @sandeepkothari โ€บ a-comprehensive-list-of-python-exceptions-a-must-read-for-python-programmers-3f4dd24f3b11
A comprehensive list of Python exceptions โ€” a must read for python programmers | by Sandeep Kothari | Medium
September 7, 2024 - Arithmetic Exceptions ZeroDivisionError: Raised when division or modulo by zero is attempted. OverflowError: Raised when the result of an arithmetic operation is too large to be represented.
๐ŸŒ
GitHub
github.com โ€บ openai โ€บ openai-python
GitHub - openai/openai-python: The official Python library for the OpenAI API ยท GitHub
When consuming a Stream or AsyncStream, read timeouts raise APITimeoutError and other HTTPX request failures raise APIConnectionError. Catch these SDK exceptions instead of raw HTTPX exceptions; the original exception is available as __cause__. Stream consumption is not automatically retried, because replaying a request could duplicate output already delivered to your application.
Author: openai
๐ŸŒ
Pandas
pandas.pydata.org โ€บ docs โ€บ reference โ€บ api โ€บ pandas.read_csv.html
pandas.read_csv โ€” pandas 3.0.5 documentation
'error', raise an Exception when a bad line is encountered. 'warn', raise a warning when a bad line is encountered and skip that line. 'skip', skip bad lines without raising or warning when they are encountered. Callable, function that will process a single bad line. With engine='python', function with signature (bad_line: list[str]) -> list[str] | None.
๐ŸŒ
Real Python
realpython.com โ€บ python-exceptions
Python Exceptions: An Introduction โ€“ Real Python
March 18, 2026 - In this beginner tutorial, you'll learn what exceptions are good for in Python. You'll see how to raise exceptions and how to handle them with try ... except blocks.
๐ŸŒ
Programiz
programiz.com โ€บ python-programming โ€บ exceptions
Python Exceptions (With Examples)
There are plenty of built-in exceptions ... Here, locals()['__builtins__'] will return a module of built-in exceptions, functions, and attributes and dir allows us to list ......
๐ŸŒ
Wikipedia
en.wikipedia.org โ€บ wiki โ€บ Python_(programming_language)
Python (programming language) - Wikipedia
2 days ago - I'd spent a summer at DEC's Systems ... about the same time. What I learned there later showed up in Python's exception handling, modules, and the fact that methods explicitly contain 'self' in their parameter list....
๐ŸŒ
Dataquest
dataquest.io โ€บ home โ€บ blog โ€บ python exceptions: the ultimate beginner's guide (with examples)
Python Exceptions: The Ultimate Beginner's Guide (with Examples)
March 6, 2023 - The parser shows the place where the syntax error was detected by a little arrow ^. Notice also that the subsequent line print(1) was not executed since the Python interpreter stopped working when the error occurred. ... --------------------------------------------------------------------------- NameError Traceback (most recent call last) ~\AppData\Local\Temp/ipykernel_4732/971139432.py in <module> ----> 1 print(x) 2 print(1) NameError: name 'x' is not defined ยท Now when we have fixed the wrong syntax, we got another type of error: an exception.
๐ŸŒ
Python Module of the Week
pymotw.com โ€บ 2 โ€บ exceptions
exceptions โ€“ Built-in error classes - Python Module of the Week
This allows cleanup code in try:finally blocks to run and special environments (like debuggers and test frameworks) to catch the exception and avoid exiting. TypeErrors are caused by combining the wrong type of objects, or calling a function with the wrong type of object. ... $ python exceptions_TypeError.py Traceback (most recent call last): File "exceptions_TypeError.py", line 12, in <module> result = ('tuple',) + 'string' TypeError: can only concatenate tuple (not "str") to tuple
๐ŸŒ
Django
docs.djangoproject.com โ€บ en โ€บ 6.0 โ€บ ref โ€บ settings
Settings | Django documentation | Django
If True, the SecurityMiddleware redirects all non-HTTPS requests to HTTPS (except for those URLs matching a regular expression listed in SECURE_REDIRECT_EXEMPT).