Skip to content

Module 12 · Exception Handling — topic 4 of 11

try

The try block: wrapping code that might fail, keeping the protected region small, what happens to the rest of the block after an error, and retry loops.

Beginner 8 min read·Lesson 186 of 306 in Python Programming

Learning objectives

  • Write try/except blocks
  • Keep try blocks small and focused
  • Build input-validation and retry loops

Definition

The try statement marks a block of code whose exceptions may be handled. If an exception is raised inside the try block, the rest of the block is skipped and Python looks for a matching except clause attached to it.

Introduction

Any line that depends on outside data — user input, files, networks — might fail. Putting it in a try block gives you a place to respond instead of crashing.

Why it matters

How much code you place in a try block matters. Too much and you might catch errors from lines you didn't expect to fail, hiding real bugs.

Detailed explanation

Syntax: try: followed by an indented block, then at least one except or finally clause.

Lines in the try block run in order. If one raises an exception, the remaining lines in the block are skipped.

If an except clause matches, its block runs and execution continues after the whole try statement.

If no clause matches, the exception propagates as if there were no try.

Keep the try block minimal: include only the lines that can raise the exception you're handling. Put follow-up work after the statement or in an else clause.

A while True loop with try inside is a common way to keep asking until valid input arrives; return or break when it succeeds.

A try block has almost no performance cost when no exception occurs, so use it freely around genuinely risky operations.

Syntax

Python
try:
n = int(text) # only the risky line
except ValueError:
print("not a number")
  • try needs except or finally.
  • The rest of the block is skipped on error.
  • Protect only the risky lines.

Code examples

A basic try/except

Python
text = "42"
try:
n = int(text)
print("parsed", n)
except ValueError:
print("not a number")
Output
parsed 42

Handling bad items in a loop

Python
for text in ["7", "seven", "3.5"]:
try:
n = int(text)
except ValueError:
print(f"{text!r} is not a whole number")
continue
print(f"{text!r} squared is {n * n}")
Output
'7' squared is 49
'seven' is not a whole number
'3.5' is not a whole number

More examples

A retry loop

Python
inputs = iter(["abc", "-4", "12"]) # stands in for input()
def ask(prompt):
return next(inputs)
def read_positive(prompt):
attempts = 0
while True:
attempts += 1
text = ask(prompt)
try:
value = int(text)
if value <= 0:
raise ValueError("must be positive")
return value, attempts
except ValueError as e:
print(f"attempt {attempts}: {text!r} rejected ({e})")
print(read_positive("Quantity: "))
Output
attempt 1: 'abc' rejected (invalid literal for int() with base 10: 'abc')
attempt 2: '-4' rejected (must be positive)
(12, 3)

Step-by-step explanation

  • The loop repeats until the try block reaches return.
  • Both a conversion failure and our own range check raise ValueError, so one handler covers both.
  • In a real program ask would call input(); an iterator stands in so the example runs on its own.

Expected output

Running “A retry loop” prints exactly:

TextOutput
attempt 1: 'abc' rejected (invalid literal for int() with base 10: 'abc')
attempt 2: '-4' rejected (must be positive)
(12, 3)

Practical applications

  • Command-line tools re-prompting for valid input.
  • Network clients retrying a failed request a few times.

Best practices

  • Wrap only the lines that can fail.
  • Limit retries in real systems so a loop can't spin forever.
  • Combine with else and finally for clean structure.

Common mistakes

A huge try block

Avoid

try:
data = load()
result = process(data)
save(result)
except ValueError:
print("bad input")

Prefer

try:
data = load()
except ValueError:
print("bad input")
else:
save(process(data))

A ValueError from process or save would be wrongly reported as bad input.

Important notes

  • The next lessons cover except, else and finally in detail.

Key takeaways

  • try marks code whose exceptions may be handled.
  • After an error the rest of the try block is skipped.
  • Keep try blocks small.

Try it yourself

  1. 1
    Write a function that keeps asking (from a list) until it gets a valid date in DD/MM/YYYY format.
  2. 2
    Rewrite a large try block so only the risky line is protected.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

10 questions cover the “Exception Handling” module. Answers and explanations are revealed after you submit.

  • ModerateWhat is printed?
  • ModerateWhat is printed?
  • ModerateWhat is printed?
Practise this module