Skip to content

Programming: Exceptions

Alexandru Jora edited this page Sep 4, 2020 · 2 revisions

In general, try not to try (if problem is anticipated, check at the source).

Below are examples of how exceptions can be handled.

General exception:

if something_right:
  # do something
elif something_wrong:
  raise Exception("Something is wrong: XYZ")

Specific exceptions:

x = 10
if x > 5:
    raise ValueError("x should not exceed 5. The value of x was: {}".format(x))

Within a try clause, for a specific exception:

try:
   1 / 0
except ZeroDivisionError:
   raise ValueError("You cannot divide by zero!")

Avoid the following pattern:

try:
   something_right
except Exception as e:
   raise Exception("Some exception occurred: {}".format(e))

This adds not value, instead let the exception occur and propagate.

In some cases, you don't need to raise the exception. Only mention it:

try:
   something_right
except Exception as e:
   logger.warning("Some exception occurred: {} but we are ignoring it".format(e))
   pass

General guidelines:

  • Try to be as specific as possible when handling exceptions (avoid catch-alls if possible)
  • Be explicit when silencing an exception

More info at: https://docs.python.org/3/tutorial/errors.html

Clone this wiki locally