Логотип Try Except

Try Except

Спільнота
hugobowne
try-except

Перевіряє блоки try/except на надто широку область дії, ризик перехоплення помилок за типом by-catch і перехоплення вбудованих винятків, для яких натомість слід використовувати умовні перевірки. Уточнює кожен блок, щоб try охоплював лише операцію, яка справді може завершитися помилкою.

Add to TypingMind

Огляд

Видавецьhugobowne
Репозиторійshow-us-your-agent-skills
Назва навичкиtry-except
Зірки
70
Форки
10
Файли в пакеті
1
ЛіцензіяMIT
Посилання
  • Інструкції у форматі Markdown

    Файл SKILL.md, який модель завантажує за потреби, тож токени витрачаються лише тоді, коли запит справді відповідає навичці.

  • Працює з будь-якою LLM

    Навички ШІ — це звичайний Markdown, а не код для певного постачальника, тому вони працюють із GPT, Claude, Gemini, Grok або локальною моделлю.

  • Файлів у комплекті: 1

    Скрипти, шаблони й довідкові матеріали, які модель може читати під час роботи. Файли доступні лише для читання й ніколи не виконуються.

  • Відкритий вихідний код

    Видавець на GitHub: hugobowne. Перед установленням перегляньте вихідні файли навички.

Встановлення

Установіть навичку ШІ Try Except у TypingMind, щоб використовувати її з будь-якою LLM, або додайте її до іншого агента, що читає SKILL.md.

1

Встановити в TypingMind

TypingMind встановлює навичку безпосередньо з її папки на GitHub — читає SKILL.md, збирає файли ресурсів у пакет і зберігає результат локально.

  1. Відкрийте застосунок і перейдіть до розділу «Плагіни» → «Навички».
  2. Виберіть «Встановити з GitHub».
  3. Вставте наведений нижче URL папки навички та підтвердьте встановлення.
    https://github.com/hugobowne/show-us-your-agent-skills/tree/main/skills/try-except
  4. Увімкніть навичку в кожному чаті, де хочете її використовувати.
Плагіни → Навички → Додати навичку → За URL GitHub, потім вставте URL папки й натисніть «Продовжити».
2

Встановити в іншому агенті

Будь-який агент, що підтримує формат Agent Skills, може використовувати цю навичку — скопіюйте папку до каталогу навичок цього агента.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/hugobowne/show-us-your-agent-skills.git /tmp/show-us-your-agent-skills
mkdir -p .claude/skills
cp -r /tmp/show-us-your-agent-skills/skills/try-except .claude/skills/try-except
Після копіювання перезапустіть Claude Code, щоб завантажити нову навичку.

Використовуйте навичку в TypingMind

Увімкніть навичку Try Except в будь-якому чаті TypingMind, і далі модель усе зробить сама. Назва й опис навички містяться в системному промпті, а щойно надходить відповідний запит, модель самостійно завантажує повні інструкції — вам не потрібно викликати навичку вручну, і до фактичного використання вона не витрачає токенів.

Модель самостійно завантажує навичку Try Except, щойно надходить відповідний запит.

Працює з будь-якою моделлю ШІ

Навички ШІ — це звичайні інструкції у форматі Markdown, а не код для певного постачальника, тому навичка Try Except не прив’язана до моделі, для якої її створено. Установіть її один раз у TypingMind і використовуйте з GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama або локальною моделлю, яку ви запускаєте самостійно, — усе з вашими власними ключами API.

  • Завантажується лише за потреби

    Системний промпт містить лише назву й опис. Інструкції завантажуються за першого відповідного запиту, тож поки навичка не потрібна, токени на її інструкції не витрачаються.

  • Змінюйте моделі під час чату

    Оскільки навичка — це інструкції, а не код, зміна моделі не порушує її роботу: наступна модель читає той самий файл SKILL.md.

Інструкції навички

Це вміст файлу SKILL.md, який завантажує модель. Прочитайте його перед установленням — навичка містить інструкції, яких дотримуватиметься ваша модель.

Project: honnibal/claude-skills. "Claude skills I'm experimenting with. Please review carefully before use."

License: MIT License. Full license text is in LICENSE alongside this file.

Snapshot: Frozen copy of 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.yif hasattr(x, "y"): or check the type
IndexError on lst[i]if i < len(lst):
TypeError on an operationcheck 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?

The try block should contain only the operation that can raise the expected exception — nothing more. Every additional statement is a potential source of by-catch.

What to look for:

  • Setup statements before the risky operation. Variable assignments, transformations, or function calls that appear before the line that actually interacts with external state. Move them above the try.

  • Processing after the risky operation. Code that uses the result of the risky operation but can't itself raise the caught exception type. Move it after the try/except (or into an else block).

  • Multiple independent risky operations. If the try block contains two unrelated operations that might both raise (e.g. opening a file and then parsing it), consider splitting into two try/except blocks so each has its own error handling.

Example — too wide:

python
# Bad: the entire block is wrapped. prepare_query() and process_rows()
# could raise KeyError from internal bugs, silently caught.
try:
    query = prepare_query(params)
    conn = db.connect(host)
    rows = conn.execute(query)
    result = process_rows(rows)
except (ConnectionError, KeyError):
    result = default_result()
python
# Good: only the operation that involves external state is in the try.
query = prepare_query(params)
try:
    conn = db.connect(host)
    rows = conn.execute(query)
except ConnectionError:
    result = default_result()
else:
    result = process_rows(rows)

Note that KeyError was also removed from the except clause — it was there to catch errors from prepare_query(), which is a local logic function that should not have its errors silenced.

3. Is the except clause too broad?

Check what exception types are caught. Rank them from most to least dangerous:

  1. Bare except: — catches everything including SystemExit, KeyboardInterrupt, and GeneratorExit. Almost never correct.
  2. except Exception: — catches all standard exceptions. Appropriate only at top-level entry points (CLI main, web request handlers, task runners) where you genuinely need a catch-all to log and continue. Anywhere else, it silences bugs.
  3. except (ExcA, ExcB, ExcC): with a long tuple — the more types you catch, the more by-catch risk. Each type should have a clear justification tied to a specific operation in the try block.
  4. except SpecificError: — good, but verify it's the right specific error for the operation in the try block.

For each caught exception type, ask: "Which exact line in the try block can raise this, and is there another line that might also raise it unintentionally?"

4. Does the handler mask failure?

Look at what happens in the except block:

  • pass — the error is completely swallowed. Is the caller aware that this operation can silently fail?
  • Returns a default value — the caller can't distinguish success from failure. Is this intentional and documented?
  • Logs and continues — better than pass, but still silences the error for the caller. Check whether the log message includes enough context to debug.
  • Re-raises or raises a different exception — usually fine, but check that the replacement exception preserves the original context (raise X from e).
  • Retries — check that there's a limit and a backoff, and that the retry makes sense for the exception type.

5. Are there nested try/except blocks?

Nested try/except is not inherently wrong, but it often signals that the outer block is too wide. Check whether the inner try/except could be moved out, or whether the whole structure could be simplified.

Common Patterns to Flag

These are patterns that are frequently wrong. Not all instances are bugs — some are intentional and appropriate — but each one deserves scrutiny.

except KeyError on a dict access

python
# Suspect — by-catch risk from any KeyError in compute_value()
try:
    value = cache[compute_key(item)]
except KeyError:
    value = compute_value(item)
    cache[compute_key(item)] = value

Fix: use key = compute_key(item) then if key in cache: / else:, or cache.get(key), or cache.setdefault(key, ...).

except AttributeError on attribute access

python
# Suspect — catches AttributeError from anywhere inside some_method()
try:
    result = obj.some_method()
except AttributeError:
    result = fallback()

Fix: use if hasattr(obj, "some_method"): or check the type. If the intent is duck-typing, use a protocol or ABC.

except TypeError as a type switch

python
# Suspect — TypeError from bugs in process() is silenced
try:
    return process(items)
except TypeError:
    return process([items])

Fix: use isinstance() to check the type explicitly.

except ValueError on a conversion

The answer depends on whether the function being called documents this exception as part of its validation API:

python
# Correct — int() is a parser. ValueError is how it reports invalid input.
# This is appropriate when text comes from outside the system.
try:
    n = int(text)
except ValueError:
    n = 0

# Correct — json.loads is a parser. JSONDecodeError (a ValueError subclass)
# is its validation API. There is no way to check validity without parsing.
try:
    data = json.loads(raw)
except json.JSONDecodeError:
    data = None

# Correct — datetime.strptime does validation as parsing.
try:
    dt = datetime.strptime(s, "%Y-%m-%d")
except ValueError:
    dt = None
python
# Suspect — text comes from internal logic. Why is it ever non-numeric?
# The ValueError signals a bug upstream, not invalid external input.
try:
    n = int(record.count_field)
except ValueError:
    n = 0

The question is: is the value being parsed something the system received from outside (user input, file content, API response), or something the system produced internally? For external input, the parser's exception is the expected validation mechanism. For internal values, a ValueError means something is already wrong upstream and catching it hides the real problem.

except Exception in the middle of logic

python
# Almost always wrong — silences all bugs in the entire block
try:
    result = complex_operation(data)
except Exception:
    logger.error("operation failed")
    result = None

Fix: identify the specific exceptions that complex_operation can raise from external state, and catch only those.

Presenting Changes

For each file you modify, write a summary like:

pipeline.py — Tightened 3 try/except blocks. load_data(): moved validate_schema(data) out of the try block (was exposing its KeyError/TypeError to the except clause). connect(): replaced except Exception with except ConnectionError. get_config(): replaced try/except KeyError with dict.get() — the try block contained a call to parse_value() whose KeyError would have been silently caught.

Call out any blocks where you suspect the broad catch is hiding an existing bug — cases where narrowing the except clause might cause currently-silenced exceptions to surface. These are the most valuable findings. The user needs to know about them before you change the error handling.

Critical Rules

  • Read before editing. Never propose changes to try/except blocks you haven't read in full context. You need to understand what every statement in the block does and what it might raise.
  • Trace callees. When a function call appears inside a try block, read that function to understand what exceptions it can raise. A KeyError from prepare_query() is a bug; a ConnectionError from db.connect() is expected. You can't tell the difference without reading both.
  • Don't remove error handling blindly. Narrowing a try/except might cause exceptions to propagate that were previously caught. This is usually desirable (it stops masking bugs), but it changes behaviour. Flag these cases to the user.
  • Preserve intentional broad catches. Top-level entry points, plugin loaders, and task runners sometimes need except Exception to prevent one failure from crashing the whole system. These are appropriate if they log the exception and are at the boundary of the system. Don't narrow them.
  • Use else blocks. When moving code out of a try block, consider whether it belongs in the else clause (runs only if no exception was raised) rather than after the entire try/except/else structure.
  • Run tests after changes. Changes to exception handling alter control flow and can break things. Always verify.
  • Ask when uncertain. If you're unsure whether a broad catch is intentional or accidental, use AskUserQuestion to ask the user before changing it.

Файли в пакеті

Модель читає ці файли за потреби, поки навичку завантажено. Вони доступні для читання й ніколи не виконуються.

Поширені запитання

Що робить навичка ШІ Try Except?

Перевіряє блоки try/except на надто широку область дії, ризик перехоплення помилок за типом by-catch і перехоплення вбудованих винятків, для яких натомість слід використовувати умовні перевірки. Уточнює кожен блок, щоб try охоплював лише операцію, яка справді може завершитися помилкою.

Навіщо використовувати Try Except у TypingMind?

Тому що ви встановлюєте її один раз і використовуєте з будь-якою моделлю. Try Except — це звичайний Markdown, а не код для конкретного постачальника, тому та сама навичка працює з GPT-5, Claude, Gemini, Grok або локальною моделлю. Ви можете змінити модель навіть посеред чату, і навичка продовжить працювати. TypingMind використовує ваші власні ключі API, тож ви платите безпосередньо постачальникам замість передплати за кожне місце користувача, а ваші навички й чати залишаються у вашому сховищі.

Як встановити Try Except у TypingMind?

Відкрийте в TypingMind Плагіни → Навички → Встановити з GitHub і вставте https://github.com/hugobowne/show-us-your-agent-skills/tree/main/skills/try-except. TypingMind прочитає файл SKILL.md, додасть супровідні файли та встановить навичку, яку можна вмикати окремо для кожного чату.

Які моделі ШІ можуть використовувати Try Except?

Будь-яка модель, яку ви підключите в TypingMind. Навички ШІ — це звичайні інструкції у форматі Markdown, а не код для конкретного постачальника, тому GPT, Claude, Gemini, Grok і локальні моделі можуть завантажувати цю навичку, коли запит їй відповідає.

Зі скількома моделями ШІ можна використовувати Try Except?

Зі скількома забажаєте. У TypingMind ви можете використовувати Try Except із будь-якою моделлю, яка підтримує навички, зокрема з GPT, Claude, Gemini, Grok, DeepSeek, Mistral чи Llama. Для цього ви використовуєте власні ключі API.

Чи безкоштовна навичка ШІ Try Except?

Так. На GitHub цю навичку публікує hugobowne за ліцензією MIT. Ви платите лише своєму постачальнику ШІ за використані токени.

Що таке навички ШІ?

Навичка ШІ — це набір інструкцій для повторного використання, який навчає модель ШІ виконувати одне конкретне завдання. Він відповідає відкритому формату Agent Skills: файл SKILL.md із назвою та описом, а також скрипти, шаблони чи довідкові файли, які можуть знадобитися моделі. Модель читає інструкції лише тоді, коли ваш запит відповідає навичці, тому встановлена навичка нічого не коштує, доки її не використано.

Чим навички ШІ відрізняються від плагінів або серверів MCP?

Плагін або сервер MCP надає моделі нові інструменти, які вона може викликати, — код, який десь виконується й повертає результат. Натомість навичка ШІ дає моделі знання й пояснює порядок дій: як підійти до завдання, яких кроків дотримуватися та яким має бути якісний результат. Навички — це звичайний Markdown, тож їм не потрібні ні сервер, ні ключ API, ні середовище виконання, і вони працюють із будь-якою моделлю.

Усі
Логотип openclaw

Claw Score

openclaw
ОрганізаціяПопулярне

Перевіряйте або оновлюйте документи зі зведеною оцінкою зрілості OpenClaw на основі кореневої таксономії, оцінок зрілості та артефактів із доказами QA, не використовуючи дані maintainer discrawl або звіти про інвентаризацію в репозиторії.

82.2K
391K
Файлів: 51
Відкрити
Логотип openclaw

Clawsweeper

openclaw
ОрганізаціяПопулярне

Використовуйте для будь-якої роботи з ClawSweeper: звітів про перевірку завдань і PR в OpenClaw, завдань із виправленнями, PR із хмарними виправленнями, команд згадки супроводжувача @clawsweeper, довірених автоматичних виправлень і автоматичного злиття, перевірених ClawSweeper, моніторингу GitHub Actions…

82.2K
391K
Файлів: 1
Відкрити
Логотип openclaw

Control Ui E2e

openclaw
ОрганізаціяПопулярне

Використовуйте під час проєктування, тестування, виправлення або розширення графічного інтерфейсу OpenClaw Control UI, зокрема для галерей стрес-тестування інтерфейсу зі зворотним зв’язком, наскрізних перевірок за допомогою Vitest + Playwright, сценаріїв Gateway із заглушками…

82.2K
391K
Файлів: 1
Відкрити
Логотип openclaw

Deslop

openclaw
ОрганізаціяПопулярне

Очищення змін у поточній гілці від AI-slop: перед автоматичним переглядом приберіть зайві коментарі, надмірні захисні перевірки, підміну типів і відхилення від стилю.

82.2K
391K
Інструкції
Відкрити

Створіть власний робочий простір зі ШІ вже зараз

Підпишіться на нашу розсилку, щоб дізнаватися про нові функції та майбутні розіграші 👇