2023-06-30 09:13:39 +02:00
This rule raises an issue when an object which doesn't derive from `BaseException` is raised.
2023-05-03 11:06:20 +02:00
== Why is this an issue?
2023-06-30 09:13:39 +02:00
Attempting to raise an object which does not derive from `BaseException` will raise a ``++TypeError++``.
2020-12-21 15:38:52 +01:00
2023-06-30 09:13:39 +02:00
If you are about to create a custom exception class, note that custom exceptions should inherit from ``++Exception++``, rather than ``++BaseException++``.
2023-05-25 14:18:12 +02:00
2023-06-30 09:13:39 +02:00
``++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.
2023-05-25 14:18:12 +02:00
2023-06-30 09:13:39 +02:00
To fix this issue, make sure that the object you're attempting to raise inherits from `BaseException`.
2023-05-25 14:18:12 +02:00
2023-06-30 09:13:39 +02:00
=== Code examples
2023-05-25 14:18:12 +02:00
2023-06-30 09:13:39 +02:00
==== Noncompliant code example
2023-05-25 14:18:12 +02:00
[source,python]
----
2023-06-30 09:13:39 +02:00
raise "Something went wrong" # Noncompliant: a string is not a valid exception
2023-05-25 14:18:12 +02:00
class A:
pass
2023-06-30 09:13:39 +02:00
raise A # Noncompliant: A does not inherit from Exception
2023-05-25 14:18:12 +02:00
----
2023-06-30 09:13:39 +02:00
==== Compliant solution
2023-05-25 14:18:12 +02:00
[source,python]
----
class MyError(Exception):
pass
raise MyError("Something went wrong")
raise MyError
----
2023-06-30 09:13:39 +02:00
*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.__
2020-12-21 15:38:52 +01:00
2023-05-03 11:06:20 +02:00
== Resources
2020-12-21 15:38:52 +01:00
2023-06-30 09:13:39 +02:00
=== Documentation
2020-12-21 15:38:52 +01:00
* 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]
2021-06-02 20:44:38 +02:00
2021-06-03 09:05:38 +02:00
ifdef::env-github,rspecator-view[]
2021-09-20 15:38:42 +02:00
'''
== Implementation Specification
(visible only on this page)
2023-05-25 14:18:12 +02:00
=== Message
Change this code so that it raises an object deriving from BaseException.
2021-09-20 15:38:42 +02:00
2021-06-08 15:52:13 +02:00
'''
2021-06-02 20:44:38 +02:00
== Comments And Links
(visible only on this page)
include::../comments-and-links.adoc[]
2023-06-22 10:38:01 +02:00
2021-06-03 09:05:38 +02:00
endif::env-github,rspecator-view[]