Skip to content

Files

Latest commit

 

History

History
37 lines (25 loc) · 1.04 KB

File metadata and controls

37 lines (25 loc) · 1.04 KB

Pattern: Use of bare except

Issue: -

Description

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:).

Example of incorrect code:

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!')

Example of correct code:

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')

Further Reading