You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
The following convention should be followed for Exception handling:
Exception handling is a must and should be mitigated.
Do not use bare except or except Exception which catches all the exception.
Always be specific on exception. E.g. catch only FileNotFoundError if you are say moving a file.
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 with Error such as MyCustomError(Exception) and use it.
Always use Exception as your parent class for user defined exceptions. Donot use BaseException.
Add traceback to your mitigation. i.e. either logging or mails. Donot pass.
The try block should be specific to desired exception. Donot use huge code chunk in try. Use else if needed.
try:
value=int(some_str)
exceptValueError: # when not using exception objectWHENsome_strISnotvalidasvalue.
exceptTypeError:
WHENsome_strISOTHERTYPEsuchas [], ()
else: #can be avoided if exceptions are handled and returned. This is in context to try block.DOSOMETHINGWITHVALUEtry:
value=int(some_str)
except (ValueError, TypeError) aserror:
HANDLEBOTHexceptionanduseexceptionobjectelse: # If neededdosomethingwhentrysucceeds.
finally:
codebasetorunanyway
finally can be used if you need to run the block whatever the case. context can be used in many cases to avoid finally.
sys.exc_info and traceback can be used for traceback.
Please read this on exceptions handling internals and leaks when referencing exceptions.
Learn more about Exception Handling and Logging in detail here