Exception Handling
The following convention should be followed for Exception handling:
Exceptionhandling is a must and should be mitigated.- Do not use bare
exceptorexcept Exceptionwhich catches all the exception.- Always be specific on exception. E.g. catch only
FileNotFoundErrorif 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
Exceptionclass primarily suffixing it withErrorsuch asMyCustomError(Exception)and use it. - Always use
Exceptionas your parent class for user defined exceptions. Donot useBaseException.
- Add traceback to your mitigation. i.e. either
loggingor mails. Donotpass. - The
tryblock should be specific to desired exception. Donot use huge code chunk intry. Useelseif 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