Pattern: Use of bare except
Issue: -
When catching exceptions, mention specific exceptions whenever possible instead of using a bare except:
clause.
A bare except:
clause will catch SystemExit
and KeyboardInterrupt
exceptions, making it harder to interrupt a program with Control-C, and can disguise other problems. If you want to catch all exceptions that signal program errors, use except Exception:
(bare except is equivalent to except BaseException:).
The following code has a bare except:
clause.
try:
user = User.objects.get(pk=user_id)
user.send_mail('Hello world')
except:
logger.error('An error occurred!')
Instead, catch specific exceptions whenever possible.
try:
user = User.objects.get(pk=user_id)
user.send_mail('Hello world')
except User.DoesNotExist:
logger.error('The user does not exist with that ID')