Skip to content
Agentmart
Submit a tool

try-except

Audit try/except blocks for overly broad scope, by-catch risk, and catches of built-in exceptions that should be conditional checks.

Skill by hugobowne

IndexedMIT★ 70
Write a review

Install

Works with Claude Code, Claude apps, Codex, Cursor, Gemini CLI, GitHub Copilot, VS Code, OpenCode, Goose, Windsurf. Read the repository before you give any tool access to your data.

npx agentmarket install skill/hugobowne-try-except

Asks which of your tools to add it to (Claude Code, Codex, Cursor, VS Code, Windsurf, Gemini CLI, Claude Desktop) and shows the change first. See https://agentmart.dev/cli.

Get the weekly diff

The weekly diff: one email a week with new agent tools, notable updates and grade changes, plus security alerts for tools you follow. Double opt-in, one-click unsubscribe.

We use your email only for this newsletter. Privacy

About

Audit try/except blocks for overly broad scope, by-catch risk, and catches of built-in exceptions that should be conditional checks. Tightens each block so the try covers only the operation that can actually fail.

Use cases: security

No reviews yet. Installed it? Reviews come from verified installers only. How reviews work

Permissions

What this skill can do and what it asks for, from its SKILL.md. Checked Oct 25, 2026.

Tools
No tools found
Secrets
None asked for
Install scripts
None found

Network hosts it talks to 1

  • codeload.github.com · found in install command

Files it touches

  • ~/.claude/skills/try-except

What's inside

Skill name
try-except
Description
Audit try/except blocks for overly broad scope, by-catch risk, and catches of built-in exceptions that should be conditional checks. Tightens each block so the try covers only the operation that can actually fail.
License
MIT
Instructions
351 lines in SKILL.md · view on GitHub

Before installing

  • Instructions call the network

Files (4)

  • LICENSE
  • README.md
  • SKILL.md
  • hero.png · images/

SKILL.md (first lines)

> **Project:** [honnibal/claude-skills](https://github.com/honnibal/claude-skills). "Claude skills I'm experimenting with. Please review carefully before use."
>
> **License:** [MIT License](https://github.com/honnibal/claude-skills/blob/main/LICENSE). Full license text is in [`LICENSE`](LICENSE) alongside this file.
>
> **Snapshot:** Frozen copy of [`try-except.md.txt`](https://github.com/honnibal/claude-skills/blob/main/try-except.md.txt) as of 2026-05-22. The maintained version lives upstream and may have evolved since this snapshot.

# Interrogate Try/Except Usage

You are now in try/except audit mode. Your job is to read Python source files,
find every `try/except` block, and evaluate whether each one is correctly
scoped, catches the right exceptions, and doesn't mask bugs.

The guiding principle: **context determines whether try/except or a conditional
check is appropriate.** Try/except is for external state you cannot control —
filesystem, network, concurrent access — where race conditions make precondition
checks unreliable. For conditions over local values, use `if`, `in`, `hasattr`,
or similar checks instead.

Built-in exceptions like `KeyError`, `AttributeError`, `TypeError`, and
`IndexError` are fire escapes — emergency exits that tell you a bug has
occurred. Catching them indiscriminately is stacking old furniture in the fire
escape: harmless until a real emergency, then fatal.

## Scope

$ARGUMENTS

- If the user names specific files or directories, scope your work to those.
- If no argument is given, work through the Python files in the current project.
- For large codebases, use `AskUserQuestion` to let the user choose which
  modules or packages to start with. Don't try to do everything at once.

## Workflow

1. **Find all try/except blocks.** Grep for `try:` across the files in scope.
   Read each file that contains them.

2. **Classify each block.** For every try/except, work through the analysis
   checklist below. Take notes before proposing any changes — you need to
   understand what each statement in the try block does and where exceptions
   might actually come from.

3. **Propose changes.** For each block that has problems, explain the issue and
   show the fix. Group your changes by file. Apply the edits after presenting
   them.

4. **Verify.** After editing, run the project's test suite and type checker if
   configured. Your changes alter control flow — they can break things. Confirm
   they don't.

Use `TaskCreate` to track progress across files when there are more than a
handful.

## Analysis Checklist

Work through these checks for every `try/except` block, in order.

### 1. Is try/except the right mechanism?

Try/except is appropriate in two situations:

**A. External state you cannot check in advance.** The operation interacts with
something outside your process where a precondition check would be unreliable
(TOCTOU races) or impossible:

- Filesystem access (`open()`, `path.read_text()`, `os.stat()`)
- Network calls (`requests.get()`, `socket.connect()`, `urllib.urlopen()`)
- Database operations
- Subprocess execution

**B. Functions whose API does validation as parsing.** Many functions have no
cheap way to check whether the input is valid — the only way to find out is to
attempt the operation. The function's exception **is** its validation API, and
try/except is the intended usage:

- `json.loads(text)` — you can't check whether a string is valid JSON without
  parsing it. Catching `json.JSONDecodeError` is correct.
- `datetime.strptime(s, fmt)` — you can't check whether a string matches a
  date format without parsing it. Catching `ValueError` is correct.
- `int(s)` / `float(s)` on external input — regex validation is fragile and
  duplicates the parser's logic. Catching `ValueError` is correct.
- `pydantic.BaseModel.model_validate(data)` — the whole point is
  validate-by-parsing. Catching `ValidationError` is correct.
- `ipaddress.ip_address(s)`, `uuid.UUID(s)`, `re.compile(pattern)` — same
  principle: the constructor **is** the validator.

The key distinction: these functions raise **their own domain-specific
exceptions** (or `ValueError` as a documented part of their API). This is
fundamentally different from catching `KeyError` on a dict lookup, where the
exception is a generic signal that something is missing and could come from
anywhere in the call stack.

Even when try/except is the right mechanism, the try block must still be
**tightly scoped** — contain only the parsing/external call, not surrounding
logic. The by-catch risk is lower (a `json.JSONDecodeError` is unlikely to come
from unrelated code) but not zero, and a tight block makes the intent clear.

**Try/except is not appropriate** for conditions over local values where a
simple check suffices:

| Instead of catching...     | Use this check instead          |
|----------------------------|---------------------------------|
| `KeyError` on `d[key]`    | `if key in d:` or `d.get(key)`  |
| `AttributeError` on `x.y` | `if hasattr(x, "y"):` or check the type |
| `IndexError` on `lst[i]`  | `if i < len(lst):`              |
| `TypeError` on an operation | check the type or use an overload |

These built-in exceptions are **generic** — they can be raised by any code at
any depth. Catching them creates by-catch risk: the `except KeyError` intended
for a dict lookup might catch a `KeyError` raised five function calls deep in a
completely unrelated operation, silently masking a real bug.

The question to ask is: **does the function I'm calling document this exception
as part of its interface, or am I catching a side effect of something going
wrong?** If `json.loads` raises `JSONDecodeError`, that's its API telling you
the input was invalid. If `prepare_query()` raises `KeyError`, that's a bug.

### 2. Is the try block minimally scoped?

From hugobowne/show-us-your-agent-skills, MIT.

More from hugobowne/show-us-your-agent-skills

Signals

Stars
70
Forks
10
Open issues
0
Last commit (this folder)
May 22, 2026 (5 months ago)

From GitHub (fetched Oct 24, 2026).

Details

License
MIT
First seen
Oct 24, 2026
Last checked
Oct 24, 2026

More from hugobowne

Cite this page

try-except skill. Agent Mart. https://agentmart.dev/skills/hugobowne-try-except (last updated 2026-10-24)