All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.sonar.l10n.py.rules.python.S5632.html Maven / Gradle / Ivy

There is a newer version: 4.23.0.17664
Show newest version

This rule raises an issue when an object which doesn’t derive from BaseException is raised.

Why is this an issue?

Attempting to raise an object which does not derive from BaseException will raise a TypeError.

If you are about to create a custom exception class, note that custom exceptions should inherit from Exception, rather than BaseException.

BaseException is the base class for all built-in exceptions in Python, including system-exiting exceptions like SystemExit or KeyboardInterrupt, which are typically not meant to be caught. On the other hand, Exception is intended for exceptions that are expected to be caught, which is generally the case for user-defined exceptions. See PEP 352 for more information.

To fix this issue, make sure that the object you’re attempting to raise inherits from BaseException.

Code examples

Noncompliant code example

raise "Something went wrong"  # Noncompliant: a string is not a valid exception

class A:
    pass

raise A  # Noncompliant: A does not inherit from Exception

Compliant solution

class MyError(Exception):
    pass

raise MyError("Something went wrong")
raise MyError

Note: In Python 2 it is possible to raise old-style classes but this shouldn’t be done in order to be compatible with Python 3.

Resources

Documentation





© 2015 - 2024 Weber Informatics LLC | Privacy Policy