Bad exception handling Info

Throwing a base or generic exception might cause important error information to be lost. This can make your code difficult to maintain. We recommend using built-in exceptions or creating a custom exception class that is derived from Exception or one of its subclasses.

Detector ID
python/bad-exception-handling-practices@v1.0
Category
Common Weakness Enumeration (CWE) external icon
-
Tags
-

Noncompliant example

1def exception_handling_noncompliant(parameter):
2    if not isinstance(parameter, int):
3        # Noncompliant: a generic exception is thrown.
4        raise Exception("param should be an integer")

Compliant example

1def exception_handling_compliant(parameter):
2    if not isinstance(parameter, int):
3        # Compliant: specific exception is thrown.
4        raise TypeError("param should be an integer")