Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Code enhancement: error handle best practise #68

Open
leyao-daily opened this issue Jul 13, 2023 · 0 comments
Open

Code enhancement: error handle best practise #68

leyao-daily opened this issue Jul 13, 2023 · 0 comments
Labels
enhancement New feature or request

Comments

@leyao-daily
Copy link

To make the code more robust and easier to debug, based on python standard, we may update our code based on the following best practises:

  1. Use Exceptions, Not Return Codes

Instead of returning error codes, it's more Pythonic to raise exceptions when something goes wrong. This makes your code cleaner and less cluttered with error-handling code.

  1. Minimize the Amount of Code in try/except Blocks

The more code that is within a try block, the more likely it will be that an exception will occur. This can make it harder to determine what is causing an error. So, limit the amount of code in your try blocks to just the part that might raise an exception.

try:
    dangerous_call()
except Exception as e:
    # Handle exception
    pass
  1. Catch Specific Exceptions

When catching exceptions, catch specific exceptions instead of just a generic Exception. This allows you to handle different types of exceptions differently and prevents you from catching exceptions that you didn't intend to catch.

try:
    dangerous_call()
except ValueError as ve:
    # Handle ValueError
    pass
except TypeError as te:
    # Handle TypeError
    pass
  1. Consider the Caller

When deciding whether to handle an exception or to let it propagate, consider who the caller is. If the caller would be in a good position to handle the exception, it may be better to let it propagate.

  1. Use Finally for Cleanup

If there are resources that need to be cleaned up (like file handles or database connections), consider using a finally block. Code in a finally block will be run whether an exception was raised or not.

try:
    dangerous_call()
except Exception as e:
    # Handle exception
    pass
finally:
    cleanup()
  1. Use Custom Exceptions (Optional)

If your library or application has errors that it might want to raise, consider defining custom exception classes. This can make it easier for users of your code to handle exceptions appropriately.

@leyao-daily leyao-daily added the enhancement New feature or request label Jul 13, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

1 participant