2023-06-30 09:13:39 +02:00

67 lines
2.0 KiB
Plaintext

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 https://www.python.org/dev/peps/pep-0352/#exception-hierarchy-changes[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
[source,python]
----
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
[source,python]
----
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
* https://docs.python.org/3/tutorial/errors.html[Python documentation - Errors and Exceptions]
* https://www.python.org/dev/peps/pep-0352/#exception-hierarchy-changes[PEP 352 - Required Superclass for Exceptions]
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== Message
Change this code so that it raises an object deriving from BaseException.
'''
== Comments And Links
(visible only on this page)
include::../comments-and-links.adoc[]
endif::env-github,rspecator-view[]