rspec/rules/S1181/cfamily/rule.adoc

63 lines
2.0 KiB
Plaintext
Raw Normal View History

== Why is this an issue?
2021-01-27 13:42:22 +01:00
Some exception classes are designed to be used only as base classes to more specific exceptions, for instance ``++std::exception++`` (the base class of all standard {cpp} exceptions), ``++std::logic_error++`` or ``++std::runtime_error++``.
2020-06-30 12:47:33 +02:00
2021-02-02 15:02:10 +01:00
2020-06-30 12:47:33 +02:00
Catching such a generic exception types is a usually bad idea, because it implies that the "catch" block is clever enough to handle any type of exception.
=== Noncompliant code example
2020-06-30 12:47:33 +02:00
2022-02-04 17:28:24 +01:00
[source,cpp]
2020-06-30 12:47:33 +02:00
----
try {
/* code that may throw std::system_error */
} catch (const std::exception &ex) { // Noncompliant
/*...*/
}
----
=== Compliant solution
2020-06-30 12:47:33 +02:00
2022-02-04 17:28:24 +01:00
[source,cpp]
2020-06-30 12:47:33 +02:00
----
try {
/* code that may throw std::system_error */
} catch (const std::system_error &ex) {
/*...*/
}
----
=== Exceptions
2020-06-30 12:47:33 +02:00
2021-01-27 13:42:22 +01:00
There are cases though where you want to catch all exceptions, because no exceptions should be allowed to escape the function, and generic ``++catch++`` handlers are excluded from the rule:
2020-06-30 12:47:33 +02:00
* In the main function
* In a class destructor
2021-01-27 13:42:22 +01:00
* In a ``++noexcept++`` function
* In an ``++extern "C"++`` function
2020-06-30 12:47:33 +02:00
2021-01-27 13:42:22 +01:00
Additionally, if the ``++catch++`` handler is throwing an exception (either the same as before, with ``++throw;++`` or a new one that may make more sense to the callers of the function), or is never exiting (because it calls a ``++noreturn++`` function, for instance ``++exit++``), then the accurate type of the exception usually does not matter any longer: this case is excluded too.
2020-06-30 12:47:33 +02:00
== Resources
* https://cwe.mitre.org/data/definitions/396[MITRE, CWE-396] - Declaration of Catch for Generic Exception
* https://github.com/isocpp/CppCoreGuidelines/blob/036324/CppCoreGuidelines.md#Re-exception-types[{cpp} Core Guidelines E.14] - Use purpose-designed user-defined types as exceptions (not built-in types)
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
include::message.adoc[]
include::highlighting.adoc[]
'''
== Comments And Links
(visible only on this page)
include::comments-and-links.adoc[]
endif::env-github,rspecator-view[]