exceptions.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658
  1. # Licensed under the GPL: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html
  2. # For details: https://github.com/pylint-dev/pylint/blob/main/LICENSE
  3. # Copyright (c) https://github.com/pylint-dev/pylint/blob/main/CONTRIBUTORS.txt
  4. """Checks for various exception related errors."""
  5. from __future__ import annotations
  6. import builtins
  7. import inspect
  8. from collections.abc import Generator
  9. from typing import TYPE_CHECKING, Any
  10. import astroid
  11. from astroid import nodes, objects, util
  12. from astroid.context import InferenceContext
  13. from astroid.typing import InferenceResult, SuccessfulInferenceResult
  14. from pylint import checkers
  15. from pylint.checkers import utils
  16. from pylint.interfaces import HIGH, INFERENCE
  17. from pylint.typing import MessageDefinitionTuple
  18. if TYPE_CHECKING:
  19. from pylint.lint import PyLinter
  20. def _builtin_exceptions() -> set[str]:
  21. def predicate(obj: Any) -> bool:
  22. return isinstance(obj, type) and issubclass(obj, BaseException)
  23. members = inspect.getmembers(builtins, predicate)
  24. return {exc.__name__ for (_, exc) in members}
  25. def _annotated_unpack_infer(
  26. stmt: nodes.NodeNG, context: InferenceContext | None = None
  27. ) -> Generator[tuple[nodes.NodeNG, SuccessfulInferenceResult]]:
  28. """Recursively generate nodes inferred by the given statement.
  29. If the inferred value is a list or a tuple, recurse on the elements.
  30. Returns an iterator which yields tuples in the format
  31. ('original node', 'inferred node').
  32. """
  33. if isinstance(stmt, (nodes.List, nodes.Tuple)):
  34. for elt in stmt.elts:
  35. inferred = utils.safe_infer(elt)
  36. if inferred and not isinstance(inferred, util.UninferableBase):
  37. yield elt, inferred
  38. return
  39. for inferred in stmt.infer(context):
  40. if isinstance(inferred, util.UninferableBase):
  41. continue
  42. yield stmt, inferred
  43. def _is_raising(body: list[nodes.NodeNG]) -> bool:
  44. """Return whether the given statement node raises an exception."""
  45. return any(isinstance(node, nodes.Raise) for node in body)
  46. MSGS: dict[str, MessageDefinitionTuple] = {
  47. "E0701": (
  48. "Bad except clauses order (%s)",
  49. "bad-except-order",
  50. "Used when except clauses are not in the correct order (from the "
  51. "more specific to the more generic). If you don't fix the order, "
  52. "some exceptions may not be caught by the most specific handler.",
  53. ),
  54. "E0702": (
  55. "Raising %s while only classes or instances are allowed",
  56. "raising-bad-type",
  57. "Used when something which is neither a class nor an instance "
  58. "is raised (i.e. a `TypeError` will be raised).",
  59. ),
  60. "E0704": (
  61. "The raise statement is not inside an except clause",
  62. "misplaced-bare-raise",
  63. "Used when a bare raise is not used inside an except clause. "
  64. "This generates an error, since there are no active exceptions "
  65. "to be reraised. An exception to this rule is represented by "
  66. "a bare raise inside a finally clause, which might work, as long "
  67. "as an exception is raised inside the try block, but it is "
  68. "nevertheless a code smell that must not be relied upon.",
  69. ),
  70. "E0705": (
  71. "Exception cause set to something which is not an exception, nor None",
  72. "bad-exception-cause",
  73. 'Used when using the syntax "raise ... from ...", '
  74. "where the exception cause is not an exception, "
  75. "nor None.",
  76. {"old_names": [("E0703", "bad-exception-context")]},
  77. ),
  78. "E0710": (
  79. "Raising a class which doesn't inherit from BaseException",
  80. "raising-non-exception",
  81. "Used when a class which doesn't inherit from BaseException is raised.",
  82. ),
  83. "E0711": (
  84. "NotImplemented raised - should raise NotImplementedError",
  85. "notimplemented-raised",
  86. "Used when NotImplemented is raised instead of NotImplementedError",
  87. ),
  88. "E0712": (
  89. "Catching an exception which doesn't inherit from Exception: %s",
  90. "catching-non-exception",
  91. "Used when a class which doesn't inherit from "
  92. "Exception is used as an exception in an except clause.",
  93. ),
  94. "W0702": (
  95. "No exception type(s) specified",
  96. "bare-except",
  97. "A bare ``except:`` clause will catch ``SystemExit`` and "
  98. "``KeyboardInterrupt`` exceptions, making it harder to interrupt a program "
  99. "with ``Control-C``, and can disguise other problems. If you want to catch "
  100. "all exceptions that signal program errors, use ``except Exception:`` (bare "
  101. "except is equivalent to ``except BaseException:``).",
  102. ),
  103. "W0718": (
  104. "Catching too general exception %s",
  105. "broad-exception-caught",
  106. "If you use a naked ``except Exception:`` clause, you might end up catching "
  107. "exceptions other than the ones you expect to catch. This can hide bugs or "
  108. "make it harder to debug programs when unrelated errors are hidden.",
  109. {"old_names": [("W0703", "broad-except")]},
  110. ),
  111. "W0705": (
  112. "Catching previously caught exception type %s",
  113. "duplicate-except",
  114. "Used when an except catches a type that was already caught by "
  115. "a previous handler.",
  116. ),
  117. "W0706": (
  118. "The except handler raises immediately",
  119. "try-except-raise",
  120. "Used when an except handler uses raise as its first or only "
  121. "operator. This is useless because it raises back the exception "
  122. "immediately. Remove the raise operator or the entire "
  123. "try-except-raise block!",
  124. ),
  125. "W0707": (
  126. "Consider explicitly re-raising using %s'%s from %s'",
  127. "raise-missing-from",
  128. "Python's exception chaining shows the traceback of the current exception, "
  129. "but also of the original exception. When you raise a new exception after "
  130. "another exception was caught it's likely that the second exception is a "
  131. "friendly re-wrapping of the first exception. In such cases `raise from` "
  132. "provides a better link between the two tracebacks in the final error.",
  133. ),
  134. "W0711": (
  135. 'Exception to catch is the result of a binary "%s" operation',
  136. "binary-op-exception",
  137. "Used when the exception to catch is of the form "
  138. '"except A or B:". If intending to catch multiple, '
  139. 'rewrite as "except (A, B):"',
  140. ),
  141. "W0715": (
  142. "Exception arguments suggest string formatting might be intended",
  143. "raising-format-tuple",
  144. "Used when passing multiple arguments to an exception "
  145. "constructor, the first of them a string literal containing what "
  146. "appears to be placeholders intended for formatting",
  147. ),
  148. "W0716": (
  149. "Invalid exception operation. %s",
  150. "wrong-exception-operation",
  151. "Used when an operation is done against an exception, but the operation "
  152. "is not valid for the exception in question. Usually emitted when having "
  153. "binary operations between exceptions in except handlers.",
  154. ),
  155. "W0719": (
  156. "Raising too general exception: %s",
  157. "broad-exception-raised",
  158. "Raising exceptions that are too generic force you to catch exceptions "
  159. "generically too. It will force you to use a naked ``except Exception:`` "
  160. "clause. You might then end up catching exceptions other than the ones "
  161. "you expect to catch. This can hide bugs or make it harder to debug programs "
  162. "when unrelated errors are hidden.",
  163. ),
  164. }
  165. class BaseVisitor:
  166. """Base class for visitors defined in this module."""
  167. def __init__(self, checker: ExceptionsChecker, node: nodes.Raise) -> None:
  168. self._checker = checker
  169. self._node = node
  170. def visit(self, node: SuccessfulInferenceResult) -> None:
  171. name = node.__class__.__name__.lower()
  172. dispatch_meth = getattr(self, "visit_" + name, None)
  173. if dispatch_meth:
  174. dispatch_meth(node)
  175. else:
  176. self.visit_default(node)
  177. def visit_default(self, _: nodes.NodeNG) -> None:
  178. """Default implementation for all the nodes."""
  179. class ExceptionRaiseRefVisitor(BaseVisitor):
  180. """Visit references (anything that is not an AST leaf)."""
  181. def visit_name(self, node: nodes.Name) -> None:
  182. if node.name == "NotImplemented":
  183. self._checker.add_message(
  184. "notimplemented-raised", node=self._node, confidence=HIGH
  185. )
  186. return
  187. try:
  188. exceptions = [
  189. c
  190. for _, c in _annotated_unpack_infer(node)
  191. if isinstance(c, nodes.ClassDef)
  192. ]
  193. except astroid.InferenceError:
  194. return
  195. for exception in exceptions:
  196. if self._checker._is_overgeneral_exception(exception):
  197. self._checker.add_message(
  198. "broad-exception-raised",
  199. args=exception.name,
  200. node=self._node,
  201. confidence=INFERENCE,
  202. )
  203. def visit_call(self, node: nodes.Call) -> None:
  204. if isinstance(node.func, nodes.Name):
  205. self.visit_name(node.func)
  206. match node.args:
  207. case [nodes.Const(value=str() as msg), _, *_]:
  208. if "%" in msg or ("{" in msg and "}" in msg):
  209. self._checker.add_message(
  210. "raising-format-tuple", node=self._node, confidence=HIGH
  211. )
  212. class ExceptionRaiseLeafVisitor(BaseVisitor):
  213. """Visitor for handling leaf kinds of a raise value."""
  214. def visit_const(self, node: nodes.Const) -> None:
  215. self._checker.add_message(
  216. "raising-bad-type",
  217. node=self._node,
  218. args=node.value.__class__.__name__,
  219. confidence=INFERENCE,
  220. )
  221. def visit_instance(self, instance: objects.ExceptionInstance) -> None:
  222. cls = instance._proxied
  223. self.visit_classdef(cls)
  224. # Exception instances have a particular class type
  225. visit_exceptioninstance = visit_instance
  226. def visit_classdef(self, node: nodes.ClassDef) -> None:
  227. if not utils.inherit_from_std_ex(node) and utils.has_known_bases(node):
  228. self._checker.add_message(
  229. "raising-non-exception",
  230. node=self._node,
  231. confidence=INFERENCE,
  232. )
  233. def visit_tuple(self, _: nodes.Tuple) -> None:
  234. self._checker.add_message(
  235. "raising-bad-type",
  236. node=self._node,
  237. args="tuple",
  238. confidence=INFERENCE,
  239. )
  240. def visit_default(self, node: nodes.NodeNG) -> None:
  241. name = getattr(node, "name", node.__class__.__name__)
  242. self._checker.add_message(
  243. "raising-bad-type",
  244. node=self._node,
  245. args=name,
  246. confidence=INFERENCE,
  247. )
  248. class ExceptionsChecker(checkers.BaseChecker):
  249. """Exception related checks."""
  250. name = "exceptions"
  251. msgs = MSGS
  252. options = (
  253. (
  254. "overgeneral-exceptions",
  255. {
  256. "default": ("builtins.BaseException", "builtins.Exception"),
  257. "type": "csv",
  258. "metavar": "<comma-separated class names>",
  259. "help": "Exceptions that will emit a warning when caught.",
  260. },
  261. ),
  262. )
  263. def open(self) -> None:
  264. self._builtin_exceptions = _builtin_exceptions()
  265. super().open()
  266. @utils.only_required_for_messages(
  267. "misplaced-bare-raise",
  268. "raising-bad-type",
  269. "raising-non-exception",
  270. "notimplemented-raised",
  271. "bad-exception-cause",
  272. "raising-format-tuple",
  273. "raise-missing-from",
  274. "broad-exception-raised",
  275. )
  276. def visit_raise(self, node: nodes.Raise) -> None:
  277. if node.exc is None:
  278. self._check_misplaced_bare_raise(node)
  279. return
  280. if node.cause is None:
  281. self._check_raise_missing_from(node)
  282. else:
  283. self._check_bad_exception_cause(node)
  284. expr = node.exc
  285. ExceptionRaiseRefVisitor(self, node).visit(expr)
  286. inferred = utils.safe_infer(expr)
  287. if inferred is None or isinstance(inferred, util.UninferableBase):
  288. return
  289. ExceptionRaiseLeafVisitor(self, node).visit(inferred)
  290. def _check_misplaced_bare_raise(self, node: nodes.Raise) -> None:
  291. # Filter out if it's present in __exit__.
  292. scope = node.scope()
  293. if (
  294. isinstance(scope, nodes.FunctionDef)
  295. and scope.is_method()
  296. and scope.name == "__exit__"
  297. ):
  298. return
  299. current = node
  300. # Stop when a new scope is generated or when the raise
  301. # statement is found inside a Try.
  302. ignores = (nodes.ExceptHandler, nodes.FunctionDef)
  303. while current and not isinstance(current.parent, ignores):
  304. current = current.parent
  305. expected = (nodes.ExceptHandler,)
  306. if not (current and isinstance(current.parent, expected)):
  307. self.add_message("misplaced-bare-raise", node=node, confidence=HIGH)
  308. def _check_bad_exception_cause(self, node: nodes.Raise) -> None:
  309. """Verify that the exception cause is properly set.
  310. An exception cause can be only `None` or an exception.
  311. """
  312. cause = utils.safe_infer(node.cause)
  313. if cause is None or isinstance(cause, util.UninferableBase):
  314. return
  315. if isinstance(cause, nodes.Const):
  316. if cause.value is not None:
  317. self.add_message("bad-exception-cause", node=node, confidence=INFERENCE)
  318. elif not isinstance(cause, nodes.ClassDef) and not utils.inherit_from_std_ex(
  319. cause
  320. ):
  321. self.add_message("bad-exception-cause", node=node, confidence=INFERENCE)
  322. def _check_raise_missing_from(self, node: nodes.Raise) -> None:
  323. if node.exc is None:
  324. # This is a plain `raise`, raising the previously-caught exception. No need for a
  325. # cause.
  326. return
  327. # We'd like to check whether we're inside an `except` clause:
  328. containing_except_node = utils.find_except_wrapper_node_in_scope(node)
  329. if not containing_except_node:
  330. return
  331. # We found a surrounding `except`! We're almost done proving there's a
  332. # `raise-missing-from` here. The only thing we need to protect against is that maybe
  333. # the `raise` is raising the exception that was caught, possibly with some shenanigans
  334. # like `exc.with_traceback(whatever)`. We won't analyze these, we'll just assume
  335. # there's a violation on two simple cases: `raise SomeException(whatever)` and `raise
  336. # SomeException`.
  337. if containing_except_node.name is None:
  338. # The `except` doesn't have an `as exception:` part, meaning there's no way that
  339. # the `raise` is raising the same exception.
  340. class_of_old_error = "Exception"
  341. if isinstance(containing_except_node.type, (nodes.Name, nodes.Tuple)):
  342. # 'except ZeroDivisionError' or 'except (ZeroDivisionError, ValueError)'
  343. class_of_old_error = containing_except_node.type.as_string()
  344. self.add_message(
  345. "raise-missing-from",
  346. node=node,
  347. args=(
  348. f"'except {class_of_old_error} as exc' and ",
  349. node.as_string(),
  350. "exc",
  351. ),
  352. confidence=HIGH,
  353. )
  354. elif (
  355. isinstance(node.exc, nodes.Call) and isinstance(node.exc.func, nodes.Name)
  356. ) or (
  357. isinstance(node.exc, nodes.Name)
  358. and node.exc.name != containing_except_node.name.name
  359. ):
  360. # We have a `raise SomeException(whatever)` or a `raise SomeException`
  361. self.add_message(
  362. "raise-missing-from",
  363. node=node,
  364. args=("", node.as_string(), containing_except_node.name.name),
  365. confidence=HIGH,
  366. )
  367. def _check_catching_non_exception(
  368. self,
  369. handler: nodes.ExceptHandler,
  370. exc: SuccessfulInferenceResult,
  371. part: nodes.NodeNG,
  372. ) -> None:
  373. if isinstance(exc, nodes.Tuple):
  374. # Check if it is a tuple of exceptions.
  375. inferred = [utils.safe_infer(elt) for elt in exc.elts]
  376. if any(isinstance(node, util.UninferableBase) for node in inferred):
  377. # Don't emit if we don't know every component.
  378. return
  379. if all(
  380. node
  381. and (
  382. utils.inherit_from_std_ex(node)
  383. or (
  384. isinstance(node, nodes.ClassDef)
  385. and not utils.has_known_bases(node)
  386. )
  387. )
  388. for node in inferred
  389. ):
  390. return
  391. if not isinstance(exc, nodes.ClassDef):
  392. # Don't emit the warning if the inferred stmt
  393. # is None, but the exception handler is something else,
  394. # maybe it was redefined.
  395. match exc:
  396. case nodes.Const(value=None):
  397. if (
  398. isinstance(handler.type, nodes.Const)
  399. and handler.type.value is None
  400. ) or handler.type.parent_of(exc):
  401. # If the exception handler catches None or
  402. # the exception component, which is None, is
  403. # defined by the entire exception handler, then
  404. # emit a warning.
  405. self.add_message(
  406. "catching-non-exception",
  407. node=handler.type,
  408. args=(part.as_string(),),
  409. )
  410. case _:
  411. self.add_message(
  412. "catching-non-exception",
  413. node=handler.type,
  414. args=(part.as_string(),),
  415. )
  416. return
  417. if (
  418. not utils.inherit_from_std_ex(exc)
  419. and exc.name not in self._builtin_exceptions
  420. ):
  421. if utils.has_known_bases(exc):
  422. self.add_message(
  423. "catching-non-exception", node=handler.type, args=(exc.name,)
  424. )
  425. def _check_try_except_raise(self, node: nodes.Try) -> None:
  426. def gather_exceptions_from_handler(
  427. handler: nodes.ExceptHandler,
  428. ) -> list[InferenceResult] | None:
  429. exceptions: list[InferenceResult] = []
  430. if handler.type:
  431. exceptions_in_handler = utils.safe_infer(handler.type)
  432. if isinstance(exceptions_in_handler, nodes.Tuple):
  433. exceptions = list(
  434. {
  435. exception
  436. for exception in exceptions_in_handler.elts
  437. if isinstance(exception, (nodes.Name, nodes.Attribute))
  438. }
  439. )
  440. elif exceptions_in_handler:
  441. exceptions = [exceptions_in_handler]
  442. else:
  443. # Break when we cannot infer anything reliably.
  444. return None
  445. return exceptions
  446. bare_raise = False
  447. handler_having_bare_raise = None
  448. exceptions_in_bare_handler: list[InferenceResult] | None = []
  449. for handler in node.handlers:
  450. if bare_raise:
  451. # check that subsequent handler is not parent of handler which had bare raise.
  452. # since utils.safe_infer can fail for bare except, check it before.
  453. # also break early if bare except is followed by bare except.
  454. excs_in_current_handler = gather_exceptions_from_handler(handler)
  455. if not excs_in_current_handler:
  456. break
  457. if exceptions_in_bare_handler is None:
  458. # It can be `None` when the inference failed
  459. break
  460. for exc_in_current_handler in excs_in_current_handler:
  461. inferred_current = utils.safe_infer(exc_in_current_handler)
  462. if any(
  463. utils.is_subclass_of(utils.safe_infer(e), inferred_current)
  464. for e in exceptions_in_bare_handler
  465. ):
  466. bare_raise = False
  467. break
  468. # `raise` as the first operator inside the except handler
  469. if _is_raising([handler.body[0]]):
  470. # flags when there is a bare raise
  471. if handler.body[0].exc is None:
  472. bare_raise = True
  473. handler_having_bare_raise = handler
  474. exceptions_in_bare_handler = gather_exceptions_from_handler(handler)
  475. else:
  476. if bare_raise:
  477. self.add_message("try-except-raise", node=handler_having_bare_raise)
  478. @utils.only_required_for_messages("wrong-exception-operation")
  479. def visit_binop(self, node: nodes.BinOp) -> None:
  480. if isinstance(node.parent, nodes.ExceptHandler):
  481. both_sides_tuple_or_uninferable = isinstance(
  482. utils.safe_infer(node.left), (nodes.Tuple, util.UninferableBase)
  483. ) and isinstance(
  484. utils.safe_infer(node.right), (nodes.Tuple, util.UninferableBase)
  485. )
  486. # Tuple concatenation allowed
  487. if both_sides_tuple_or_uninferable:
  488. if node.op == "+":
  489. return
  490. suggestion = f"Did you mean '({node.left.as_string()} + {node.right.as_string()})' instead?"
  491. # except (V | A)
  492. else:
  493. suggestion = f"Did you mean '({node.left.as_string()}, {node.right.as_string()})' instead?"
  494. self.add_message("wrong-exception-operation", node=node, args=(suggestion,))
  495. @utils.only_required_for_messages("wrong-exception-operation")
  496. def visit_compare(self, node: nodes.Compare) -> None:
  497. if isinstance(node.parent, nodes.ExceptHandler):
  498. # except (V < A)
  499. suggestion = (
  500. f"Did you mean '({node.left.as_string()}, "
  501. f"{', '.join(o.as_string() for _, o in node.ops)})' instead?"
  502. )
  503. self.add_message("wrong-exception-operation", node=node, args=(suggestion,))
  504. @utils.only_required_for_messages(
  505. "bare-except",
  506. "broad-exception-caught",
  507. "try-except-raise",
  508. "binary-op-exception",
  509. "bad-except-order",
  510. "catching-non-exception",
  511. "duplicate-except",
  512. )
  513. def visit_trystar(self, node: nodes.TryStar) -> None:
  514. """Check for empty except*."""
  515. self.visit_try(node)
  516. def visit_try(self, node: nodes.Try) -> None:
  517. """Check for empty except."""
  518. self._check_try_except_raise(node)
  519. exceptions_classes: list[Any] = []
  520. nb_handlers = len(node.handlers)
  521. for index, handler in enumerate(node.handlers):
  522. if handler.type is None:
  523. if not _is_raising(handler.body):
  524. self.add_message("bare-except", node=handler, confidence=HIGH)
  525. # check if an "except:" is followed by some other
  526. # except
  527. if index < (nb_handlers - 1):
  528. msg = "empty except clause should always appear last"
  529. self.add_message(
  530. "bad-except-order", node=node, args=msg, confidence=HIGH
  531. )
  532. elif isinstance(handler.type, nodes.BoolOp):
  533. self.add_message(
  534. "binary-op-exception",
  535. node=handler,
  536. args=handler.type.op,
  537. confidence=HIGH,
  538. )
  539. else:
  540. try:
  541. exceptions = list(_annotated_unpack_infer(handler.type))
  542. except astroid.InferenceError:
  543. continue
  544. for part, exception in exceptions:
  545. if isinstance(
  546. exception, astroid.Instance
  547. ) and utils.inherit_from_std_ex(exception):
  548. exception = exception._proxied
  549. self._check_catching_non_exception(handler, exception, part)
  550. if not isinstance(exception, nodes.ClassDef):
  551. continue
  552. exc_ancestors = [
  553. a
  554. for a in exception.ancestors()
  555. if isinstance(a, nodes.ClassDef)
  556. ]
  557. for previous_exc in exceptions_classes:
  558. if previous_exc in exc_ancestors:
  559. msg = f"{previous_exc.name} is an ancestor class of {exception.name}"
  560. self.add_message(
  561. "bad-except-order",
  562. node=handler.type,
  563. args=msg,
  564. confidence=INFERENCE,
  565. )
  566. if self._is_overgeneral_exception(exception) and not _is_raising(
  567. handler.body
  568. ):
  569. self.add_message(
  570. "broad-exception-caught",
  571. args=exception.name,
  572. node=handler.type,
  573. confidence=INFERENCE,
  574. )
  575. if exception in exceptions_classes:
  576. self.add_message(
  577. "duplicate-except",
  578. args=exception.name,
  579. node=handler.type,
  580. confidence=INFERENCE,
  581. )
  582. exceptions_classes += [exc for _, exc in exceptions]
  583. def _is_overgeneral_exception(self, exception: nodes.ClassDef) -> bool:
  584. return exception.qname() in self.linter.config.overgeneral_exceptions
  585. def register(linter: PyLinter) -> None:
  586. linter.register_checker(ExceptionsChecker(linter))