A Python exception is the language telling you that an operation could not finish in the way you asked for. The try, except, else, and finally block is how you decide what to do about it. You catch the errors that you can handle, you let the rest crash loudly so that you learn about them, and you make sure that cleanup happens either way.
The previous lesson in this module covered "Paths Done Right with pathlib", and the next lesson in this module is about "Custom Exceptions and Exception Chaining".
Here is the whole shape of it. try holds the code that might fail. except catches specific exception types and runs a handler. else runs only when the try block finished without raising anything. finally runs no matter what happens, after except and else have had their turn. raise is the verb that you use to signal an error yourself, either when you caught something and want to send it on with a better message, or when you are checking input and the data is simply wrong.
What does each clause of the block actually do?
The order of the clauses is not a style choice, because Python always evaluates them in the same fixed sequence. The differences between else and finally are the part that people mix up most often.
| Clause | Runs when | Typical job |
|---|---|---|
try | always | the risky work |
except | only if a matching error was raised | recover, translate, or re-raise |
else | only if try succeeded with no exception | the success path, kept separate from the try body |
finally | always, last | cleanup: close files, release locks, log |
def risky(value):
if value < 0:
raise ValueError('value must not be negative')
return value * 2
for probe in (5, -1):
try:
print('result:', risky(probe))
except ValueError as exc:
print('caught:', exc)
else:
print('no error on this pass')
finally:
print('finally runs every time')
Look closely at the order of the output. The else block runs before the finally block. When the try body raises an error, else is skipped completely, and finally still runs.
How do you catch only the errors you expect?
Catch by exception type, and catch the narrowest type that covers your situation. except ValueError says "I know exactly which failure this is", and it lets everything else travel upwards. That is what you want, because an unexpected exception that reaches the top level is how you find out that you have a bug.
Catching Exception is a deliberate decision and not a default. It is the right call when you genuinely want to handle any ordinary failure, such as a network call, a database query, or a third-party library, and you want to produce one consistent error message. It is the wrong call when it hides a TypeError that means your own code is broken.
def parse(text):
return int(text)
for probe in ('42', 'abc'):
try:
print('parsed:', parse(probe))
except ValueError:
print('not a number:', probe)
except TypeError:
print('wrong type:', probe)
except Exception:
print('something else entirely')
The as keyword binds the raised exception to a name so that you can read its message. That name is deleted when the handler ends, so do not try to use it afterwards. Use str(exc) when you want the message, repr(exc) when you want the type and the arguments together, and exc.args when you want the raw tuple that was passed to the constructor.
How do you raise an error yourself, and how do you re-raise one?
raise SomeError("message") tells the caller that the current operation cannot continue. It is the right move whenever a function receives input that it cannot handle, or whenever it notices a state that makes going on pointless. The exception type should tell the caller what kind of problem it is, and the message should tell a human being what went wrong.
Inside an except block, a bare raise sends the exception on again and keeps the original traceback. If you want to add some context first, then catch the original error and raise a new one that explains it better.
class ConfigError(Exception):
pass
def load(path):
with open(path, encoding='utf-8') as handle:
for line in handle:
if '=' not in line:
raise ConfigError(f"missing '=' in {line!r}")
try:
load('settings.ini')
except OSError as exc:
problem = ConfigError(f'cannot read settings.ini: {exc}')
print('translated:', problem)
print('original was:', type(exc).__name__)
Raising a new exception inside an except block still records the original one as the implicit context, even when you leave out the from keyword, so the traceback shows both errors. The link between them is only implicit though, and the from keyword makes it explicit. That is the subject of the next lesson.
Why should the success path go in else instead of in try?
Putting everything inside the try block means that a bug in your success path is caught by your own error handler, and it gets reported as if it were a failure of the risky operation. The else clause keeps the danger zone narrow, because only the genuinely risky call is protected.
def only_the_risky_call_is_protected():
try:
value = int('42')
except ValueError:
print('never reached')
else:
result = value * 2
print('success path lives in else:', result)
only_the_risky_call_is_protected()
The same reasoning applies to finally. It is the right home for cleanup that has to happen on every path, such as closing a file, releasing a lock, or rolling back a transaction. It is the wrong home for anything that can raise an error itself, because an exception inside finally replaces the exception that you were already handling.
What is the difference between raise and assert?
assert is for internal rules of your own code. It means "if this is false, then the code underneath is broken and I want to know right now". Python skips it completely when it runs with the -O optimisation flag, so you must never use it to check user input or data that came from a file. raise is the mechanism for real error handling, and it always runs.
One more thing is worth knowing. Exceptions are for exceptional situations and not for ordinary branching. If a function returns a value that you are going to check in fifty different ways, then returning that value is clearer than raising an exception and catching it again just to carry the value along.
Recap
elseruns only on success, andfinallyruns on every path, last of all.- Catch the narrowest exception type that you can handle, and order your handlers from specific to general.
except Exceptionis a decision, so use it when you really do mean "any ordinary failure".- Use
raiseto report invalid input or impossible states, and use a bareraiseto send the same error on unchanged. assertdocuments a rule and disappears under-O. Never use it to validate user data.
Try it yourself: a safe config loader
Write a function load_config(path) that reads a small text file and returns the key and value pairs as a dictionary. It should raise a ValueError when a line has no = in it, and it should let FileNotFoundError travel to the caller untouched.
Now write the caller. It should catch FileNotFoundError and print a friendly message, catch ValueError and print the number of the offending line, and use a finally block to print a "config load finished" marker no matter what happens. Then break one line in your test file on purpose and confirm that each handler fires for the right reason.