Exception Handling
The following convention should be followed for Exception
handling:
Exception
handling is a must and should be mitigated.- Do not use bare
except
orexcept Exception
which catches all the exception.- Always be specific on exception. E.g. catch only
FileNotFoundError
if you are say moving a file.
- Always be specific on exception. E.g. catch only
- User Defined Exceptions:
- Write your custom error only when your error is not described or fulfilled by internal exceptions.
- Create custom
Exception
class primarily suffixing it withError
such asMyCustomError(Exception)
and use it. - Always use
Exception
as your parent class for user defined exceptions. Donot useBaseException
.
- Add traceback to your mitigation. i.e. either
logging
or mails. Donotpass
. - The
try
block should be specific to desired exception. Donot use huge code chunk intry
. Useelse
if needed.
try:
value = int(some_str)
except ValueError: # when not using exception object
WHEN some_str IS not valid as value.
except TypeError:
WHEN some_str IS OTHER TYPE such as [], ()
else: #can be avoided if exceptions are handled and returned. This is in context to try block.
DO SOMETHING WITH VALUE
try:
value = int(some_str)
except (ValueError, TypeError) as error:
HANDLE BOTH exception and use exception object
else: # If needed
do something when try succeeds.
finally:
codebase to run anyway