try Exception handling

Last updated: 2026-09-22

try Exception handling

try wraps code that may raise; except handles, finally cleans up.

CategoryKeywords & Statements
KindKeyword / Statement
Python Versionall

📝 Syntax

try:
    block
except [ExceptionType [as name]]:
    handler
[finally:
    cleanup]

▶ Example

Edit the code, press Run, and see the result in the output panel:

Output:

caught: invalid literal for int() with base 10: 'x'
More case studies coming soon — check back later.

❓ FAQ

QWhat is the execution order of `try`/`except`/`else`/`finally`?
AFirst the `try` block runs. If it raises no exception, the `else` (if present) runs next, and finally `finally` runs regardless of exceptions. If an exception is raised, the `else` is skipped, a matching `except` runs, and then `finally` runs last.
QWhat happens if no exception type follows `except`?
AIt catches every exception, including ones you usually should not swallow like `KeyboardInterrupt` and `SystemExit`. A bare `except` is generally discouraged; prefer `except Exception:` or a more specific type.
QCan variables assigned inside the `try` block be used in the `except` block?
AYes. Python has no block-level scoping, so as long as `try` reaches the assignment line, the variable is accessible in `except`, `else`, `finally`, and after the `try` statement.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏