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.
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
- 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
parsed 42
Handling bad items in a loop
'7' squared is 49 'seven' is not a whole number '3.5' is not a whole number
More examples
A retry loop
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:
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
Prefer
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
- 1Write a function that keeps asking (from a list) until it gets a valid date in DD/MM/YYYY format.
- 2Rewrite 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?