From 38adc7f7029a1392abf9227eae8784dd0bd1cc8e Mon Sep 17 00:00:00 2001 From: Will Lachance Date: Sat, 18 Jan 2025 11:23:43 -0500 Subject: [PATCH] TRY300: Add some extra notes on not catching exceptions you didn't expect (#15036) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Summary Added some extra notes on why you should have focused try...except blocks to [TRY300](https://docs.astral.sh/ruff/rules/try-consider-else/). When fixing a violation of this rule, a co-worker of mine (very understandably) asked why this was better. The current docs just say putting the return in the else is "more explicit", but if you look at the [linked reference in the python documentation](https://docs.python.org/3/tutorial/errors.html) they are more clear on why violations like this is bad: > The use of the else clause is better than adding additional code to the [try](https://docs.python.org/3/reference/compound_stmts.html#try) clause because it avoids accidentally catching an exception that wasn’t raised by the code being protected by the try … except statement. This is my attempt at adding more context to the docs on this. Open to suggestions for wording! --------- Co-authored-by: dylwil3 --- .../src/rules/tryceratops/rules/try_consider_else.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/crates/ruff_linter/src/rules/tryceratops/rules/try_consider_else.rs b/crates/ruff_linter/src/rules/tryceratops/rules/try_consider_else.rs index 65699ca682..7b211b3f72 100644 --- a/crates/ruff_linter/src/rules/tryceratops/rules/try_consider_else.rs +++ b/crates/ruff_linter/src/rules/tryceratops/rules/try_consider_else.rs @@ -12,8 +12,10 @@ use crate::checkers::ast::Checker; /// /// ## Why is this bad? /// The `try`-`except` statement has an `else` clause for code that should -/// run _only_ if no exceptions were raised. Using the `else` clause is more -/// explicit than using a `return` statement inside of a `try` block. +/// run _only_ if no exceptions were raised. Returns in `try` blocks may +/// exhibit confusing or unwanted behavior, such as being overridden by +/// control flow in `except` and `finally` blocks, or unintentionally +/// suppressing an exception. /// /// ## Example /// ```python