Python Try Except: Handling Errors with Examples
Stop one bad input from crashing your program. Catch the errors you expect and always clean up with finally.
- try, except, else and finally
- Catching specific exceptions such as ValueError
- Raising your own errors
- 1
try: int(text)Python tries the risky line - 2
except ValueError:The error is caught - 3
finally:Clean-up runs either way
The paths through try / except
The problem
Some things can fail even in correct code: a user types "abc" where a number is expected, a file is missing, a network call times out. Without handling, the program stops with a long error. You want to react calmly instead: show a clear message, use a default, try again.
Think of it like this
try / except is like a safety net under a trapeze artist. The act runs normally in the try part. If the artist slips, the net (except) catches that fall and the show goes on. finally is the bow at the end that happens whether the act succeeded or not.
try:🎪 Try the risky moveexcept ValueError:🕸️ The net for this kind of fallprint("Please provide a valid integer")🙂 Recover with a clear messagefinally:🙇 Always happens at the endtry runs code that might fail; if an exception of the type named in except happens, Python runs that block instead of stopping, and finally runs in every case.
Key points
int(value)fails because"not-a-number"is not digits, soprint(number)insidetrynever runs.except ValueError:catches exactly that kind of error and prints a friendly message.finally:runs whether the conversion worked or not, so"Conversion finished"is always printed.- Name the error type you expect; a bare
except:would also hide real bugs.
When should you use it?
- Converting user input that might not be valid.
- Reading files or calling web services that might be unavailable.
- Cleaning up (closing a file, a connection) even when something went wrong.
When not to use it
- Checking something you can test simply, such as an empty list: an
ifis clearer. - Hiding a bug: catching every error makes the program continue with wrong data.
Example code
value = "not-a-number"
try:
number = int(value)
print(number)
except ValueError:
print("Please provide a valid integer")
finally:
print("Conversion finished")
Result of running the code
Please provide a valid integer
Conversion finished
Code explanation
The except clause handles a specific conversion error. Finally runs whether conversion succeeds or fails.
Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.
Practice exercises
Modify the runnable example with the exercises below to build understanding beyond copying the result.
- Change the input and predict the output before running.
- Handle empty or invalid input.
- Wrap the logic in a function and add more test cases.
Python try and except at a glance
try: ... except ValueError: ... | Run code and handle one kind of error |
except (ValueError, TypeError): | Handle several kinds of error the same way |
except ValueError as error: | Get the error object, for example to print its message |
else: | Runs only when the try block raised no error |
finally: | Always runs, error or not (good for cleanup) |
raise ValueError("Age must be positive") | Raise an error yourself |
raise | Inside except: re-raise the current error |
class OutOfStock(Exception): pass | Define your own exception type |
with open("data.txt") as f: | Close the file automatically, even when an error happens |
Common mistakes with try and except
A bare except that catches everything
except: also catches KeyboardInterrupt and real bugs, which hides problems. Catch the errors you expect.
try:
age = int(text)
except:
age = 0
try:
age = int(text)
except ValueError:
age = 0
Silently ignoring errors
except Exception: pass throws away the error, so nothing tells you what went wrong. At least log or print it.
try:
save(report)
except Exception:
pass
try:
save(report)
except OSError as error:
print(f"Could not save the report: {error}")
Catching the general error before the specific one
except blocks are checked in order, so a broad Exception first means the specific block never runs.
try:
value = int("abc")
except Exception:
print("Something failed")
except ValueError:
print("Not a number") # never reached
try:
value = int("abc")
except ValueError:
print("Not a number")
except Exception:
print("Something failed")
Frequently asked questions
What is the difference between except, else and finally?
except runs when the try block raises a matching error, else runs when it raises no error, and finally always runs at the end, which makes it the place for cleanup.
How do I catch multiple exceptions in Python?
List them in a tuple, except (ValueError, KeyError):, to handle them the same way, or write several except blocks to handle each one differently.
How do I print the error message?
Name the error with as: except ValueError as error: print(error). Use traceback.print_exc() to see the full traceback.
How do I create my own exception?
Define a class that inherits from Exception, such as class OutOfStock(Exception): pass, then raise it with raise OutOfStock("No more pears").
Finished this lesson?
Mark it as learned to track your progress.
Practice with a challenge
Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.
- Sum the Valid Numbers Add up the entries that are whole numbers and skip everything else, the way try/except handles bad input. Easy
- First Invalid Age Validate typed ages and report where the first bad entry is instead of letting the program crash. Easy