HexLibraryHexLibrary
</> HexCodeSign inSign up
PythonJavaScriptTypeScriptCC++JavaPHPGoRustRubyBashSQLLuaPerlCOBOLPascalDelphiFortranDartSwiftC#JuliaGroovyRElixirHaskellKotlinScalaClassic ASPClipperMS-DOS
LESSONS
Introduction to Python: Print and RepeatVariablesData Types & NumbersStringsListsConditions (if / elif / else)Loops (for / while)FunctionsOperatorsDictionariesTuples & SetsError Handling (try / except)Classes (Object-Oriented)File OperationsComments & IndentationBooleans (True / False)Lambda & map / filterModules (import)InheritanceVariable Scope
REFERENCE
📖 Overview
🖥️ Output & Input
🔢 Numbers & Math
✍️ String
📋 List
🗂️ Dictionary & Set
🔁 Condition & Loop
🧩 Function
📁 File & Error
🔄 Type & Conversion
Python›Error Handling (try / except)

Error Handling (try / except)

Catching errors without the program crashing, different error types, and the finally block.

Simple enough for a 5-year-old to understand

try / except: prevent a crash

You put risky code inside try; if an error occurs the program doesn't stop — the except block runs and it continues.

Division-by-zero error
1
try:
"Risky code starting".
Code"Risky code starting".
2
result = 10 / 0
Division by zero — raises an error.
CodeDivision by zero — raises an error.
3
except ZeroDivisionError:
Catch that error.
ConditionCatch that error.
4
print("Cannot be divided by zero")
Writes this without the program crashing.
Output / InputWrites this without the program crashing.
CodeConditionOutput / Input
💡 Hint: Without try/except the program would raise an error and stop. This structure rescues it gracefully.

🎯 Exercise & Practice

Test what you've learned — answer, write code, check instantly. (1 left)

1.What is try/except for?

About this topic

Programs throw errors: file not found, user enters letters instead of numbers, internet connection drops. Trying to check all of these one by one in advance is both difficult and you'll miss some cases. The try and except block makes this uncertainty manageable by saying "try this; if there's an error, do that".

The goal of error handling is NOT to hide errors. The goal is for the program to continue gracefully when it encounters an expected problem — showing a friendly message to the user, falling back to a default value, or retrying the operation. Code that swallows errors silently produces the hardest bugs to solve.

What you will learn

  • Catching errors with try and except
  • Handling specific error types separately
  • When else and finally blocks execute
  • Raising your own errors with raise
  • Reading messages from error objects

When to use?

Error handling is needed around everything outside your control: reading files, network requests, database queries, user input conversion. The failure of these operations is not an exception, but a normal possibility.

Conversely, wrapping logic errors in your own code with try is wrong: there, an error is a flaw that needs to be fixed, not a condition to be caught.

Common mistakes

Wrong

try:
    risky()
except:
    pass

A bare except catches ALL errors — even the Ctrl+C interrupt signal and memory errors. Combined with pass, the error completely disappears; the program runs incorrectly but leaves no trace. It is the worst anti-pattern that makes debugging impossible.

Correct

try:
    risky()
except ValueError as err:
    print("Invalid value:", err)

Wrong

try:
    value = int(text)
except Exception:
    value = 0
print(value)

Catching Exception works, but it hides what the problem actually is; a NameError caused by a typo also silently turns into zero. Explicitly writing the error type you expect ensures that unexpected errors remain visible.

Correct

try:
    value = int(text)
except ValueError:
    value = 0
print(value)

Wrong

f = open("data.txt")
data = f.read()
f.close()

If an error occurs during reading, the close line is never reached and the file stays open. The with block guarantees that the file is closed whether an error occurs or not.

Correct

with open("data.txt") as f:
    data = f.read()

Frequently asked questions

How do I know which error type to catch?

The most practical way is to run the code with an error once and read the first word of the message: such as ValueError, KeyError, FileNotFoundError. The error message tells you the type to catch directly. Doing this is much healthier than guessing and catching Exception.

When does the finally block execute?

In every case: whether an error occurs or not, even if there is a return inside try. That's why cleanup tasks — closing files, releasing connections — are written inside finally. In most cases, the with block does this job more cleanly.

Can I re-raise an error after catching it?

Yes, if you write a bare raise inside an except block, the same error is propagated upward just as it was. This is used when you want to log the error and leave it to the upper layer; this allows you to both see the error and not hide it.

Summary

try and except are for managing failures of operations outside your control; the goal is not to hide the error but to continue meaningfully. The combination of a bare except and a silent pass is the worst anti-pattern to avoid.

HexLibraryHexLibrary

Learn programming more clearly. Every command is explained line by line with colors, reinforced with runnable exercises, test your code instantly — all in one place, free.

Learn

  • Home
  • Languages & Lessons
  • HexCode

Company

  • About
  • Contact

Legal

  • Privacy Policy
  • Terms of Use

Other Projects

  • HexToolz
  • Free Service Manuals
© 2026 HexLibrary · The clearest way to learn code