Manually raising (throwing) an exception in Python
⚡TLDR
Create a Python exception with the raise
(+) exception type:
Alternatively, without additional information:
This halts code execution immediately and can be dealt with try...except
constructs.
Use the proper exception
Although you can initiate an exception easily, selecting the proper one is essential for maintainable code:
- Use
ValueError
when the function's expectations aren't met by the input. - If the argument is of an incorrect type, use the
TypeError
. - When a search in a collection fail, go for
KeyError
orIndexError
. - Use
AssertionError
when the expected condition turns out to be false. - For an unrecoverable error situation, use
SystemExit
to exit the script smoothly.
Remember, using specific exceptions helps debugging process by letting developers understand and fix the issue quickly.
Custom exceptions? Yes, you can!
Creating custom exceptions:
- Start by subclassing an existing exception class:
- Add extra context by overriding
__init__
: - Be sure to represent and handle them precisely in
try...except
:
The name of your custom exception class can be your personal code-warning!
Exception chaining: Like a detective story!
Use exception chaining to keep the original error story intact. This helps significantly with debugging and understanding the root causes:
Doing this keeps the original traceback info intact, rendering Sherlock Holmes level details to trace the bugs.
Practices to swear by when raising exceptions
- Convey the context. Always supply a message:
- Inside an
except
block, simply useraise
to keep the history: - Make a group exception catch with
except (TypeError, ValueError)
. - Log before you relaunch to keep a record for solving mysteries:
- Format and customise exception strings with
.format()
for readability and to include variables: "Just{'cause'}
we felt like it".
Linked
Linked
Was this article helpful?