How to Use try except in Python: Simple Error Handling Guide
In Python, use
try to run code that might cause an error and except to catch and handle that error without stopping the program. This helps your program continue running even if something goes wrong.Syntax
The try except block has two main parts: try where you put code that might cause an error, and except where you handle the error if it happens.
You can also specify the type of error to catch or use a general except to catch all errors.
python
try: # code that might cause an error pass except SomeError: # code to handle the error pass
Example
This example shows how to catch a division by zero error and print a friendly message instead of crashing.
python
try: result = 10 / 0 except ZeroDivisionError: print("You can't divide by zero!")
Output
You can't divide by zero!
Common Pitfalls
One common mistake is using a bare except without specifying the error type, which can hide unexpected bugs. Another is putting too much code inside try, making it hard to know what caused the error.
Always catch specific errors and keep try blocks small.
python
try: # risky code value = int(input("Enter a number: ")) print(10 / value) except: print("Something went wrong") # Too general # Better way: try: value = int(input("Enter a number: ")) print(10 / value) except ValueError: print("Please enter a valid number.") except ZeroDivisionError: print("Cannot divide by zero.")
Quick Reference
Use try to test code, except to handle errors, and optionally else for code that runs if no error happens. Use finally to run code no matter what.
python
try: # code that might fail pass except SomeError: # handle error pass else: # runs if no error pass finally: # runs always pass
Key Takeaways
Use try except to catch and handle errors without stopping your program.
Catch specific error types to avoid hiding bugs.
Keep try blocks small to easily find error causes.
Use else for code that runs only if no error occurs.
Use finally to run code regardless of errors.