In Python, try and except let you respond to a specific runtime error instead of letting it stop your program. Put only the operation that may fail inside try, catch the exception you expect, and use else for success-only work or finally for cleanup.
What does try and except do in Python?
Python runs the statements inside the try suite first. If one raises an exception that an except clause names, Python skips the rest of the try suite and runs the first matching handler. If nothing raises an exception, the handlers are skipped.
As an Amazon Associate I earn from qualifying purchases.
An exception that does not match a handler continues outward to an enclosing try, if there is one. If no handler catches it, Python reports the unhandled error. The exception can also come from a function called inside the try suite.
What is the difference between a syntax error and an exception?
A SyntaxError means Python could not parse the code—for example, a missing colon after a statement header. An exception is raised while code is executing. The Python tutorial’s examples include ZeroDivisionError for division by zero, NameError for using an undefined name, and TypeError for adding a string to an integer. try/except handles exceptions during execution; it does not repair malformed syntax that prevents the program from being parsed.
#1 Best Overall
How do I catch an error in Python?
Catch the specific error you expect from the operation. Converting text with int(), for example, raises ValueError when the text is not a valid integer.
text = input("Enter a whole number: ")
try:
number = int(text)
except ValueError:
print("Please enter digits that form a whole number.")
else:
print(f"You entered {number}.")
Here, the try suite contains only the conversion that may fail. The handler responds to invalid numeric text. The else block runs only if conversion succeeds; because it is outside the protected suite, a separate bug in the success path will not be mistaken for invalid input.
Rank #2
Choose a handler that matches the problem
A handler runs in response to a matching exception; it does not automatically fix the cause. Your program must decide what to do next: ask for new input, retry, report failure, or let the exception propagate. Catch the narrowest expected exception rather than wrapping a large block in except Exception “just in case.” Broad handling can hide unrelated programming mistakes.
The Tool Desk
Outbyte Driver Updater FREEScan for outdated or missing drivers - takes under a minuteDriver Scan →Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →When should I use else or finally?
These clauses have different jobs: except responds to an error, else runs code only after success, and finally performs cleanup as the statement exits.
| Clause | When it runs | Use it for |
|---|---|---|
except |
When an exception from the try suite matches its type |
Handling an expected failure, such as invalid input |
else |
When the try suite finishes without an exception |
Success-only work that should not be inside the protected suite |
finally |
As the try statement exits, whether or not an exception occurred |
Cleanup that must run on either path |
Use else for the success path
Place else after the except clauses. Keeping success-only statements there narrows the code that the handler can catch. The Python tutorial explains that this avoids accidentally catching an exception raised by code outside the operation being protected.
Use finally for cleanup
finally is not another error handler: it runs during exit whether an exception occurred or not, and does not itself resolve that exception. It is useful for cleanup that must happen on both success and failure. Avoid return, break, or continue inside finally; these can discard a pending exception or replace a return value. Python 3.14 emits a SyntaxWarning for these statements in finally.
How do I report an exception and raise it again?
If a handler cannot resolve an error, it can pass the active exception onward with raise. This example prints the exception details and then raises the same exception again; it reports the problem but does not recover from invalid input.
Do these 3 things before closing this tab:
1Repair Windows errors before they cause bigger problems2Scan for outdated or missing drivers - takes under a minute3Clear out junk files and repair common Windows errorstry:
number = int(text)
except ValueError as err:
print(f"Invalid number: {err}")
raise
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Where can I learn more?
The official Python tutorial’s Errors and Exceptions chapter covers handlers, exception types, and else in the Python 3.14.7 tutorial. The execution model reference describes finally behavior in Python 3.14.8.
Best Value
For a book-length beginner path, Penguin Random House lists Eric Matthes’s Python Crash Course, 3rd Edition as a Python introduction, with a section titled “Chapter 10: Files and Exceptions.” The publisher lists the paperback at 552 pages, published January 10, 2023; those details do not make the book necessary to learn this feature. See the publisher’s book page.
Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.




