Python Errors and Exceptions: How to Use try, except, else and finally
P8.1 How to Read a Python Error Message (Traceback)
Why. Beginners panic at red text. But the message tells you the line and the reason. Reading it calmly fixes most bugs in minutes.
What. A traceback lists where the error happened. The last line has the error type and the reason.
How.
Read any error
- Go to the last line first.
- Read the error type (e.g. ValueError).
- Read the message after the colon.
- Look one line up for the line number in your code.
- Fix that line and run again.
Worked example A — A ValueError.
Step 1 — What we do. We convert a bad amount from a bank file.
Step 2 — Type and run this code.
amount = float("12.5.0")
Step 3 — Output you should see.
ValueError: could not convert string to float: '12.5.0'
Step 4 — What it means. ValueError means the value has the right type (text) but bad content. The message even shows the bad text.
Worked example B — A KeyError.
Step 1 — What we do. We read a column that does not exist in a record.
Step 2 — Type and run this code.
order = {"id": 1, "amount": 450}
print(order["price"])
Step 3 — Output you should see.
KeyError: 'price'
Step 4 — What it means. KeyError: the key "price" is not there. Check spelling or use .get().
Ravindra Bagale's Tip
Copy the last line of the error into a search engine. Thousands of people have solved the same error before.
Ravindra Bagale's Tip – मराठी
Error ची शेवटची line search engine मध्ये copy करा. हजारो लोकांनी तीच error आधी सोडवली आहे.
Ravindra Bagale's Tip – हिंदी
Error की आख़िरी line search engine में copy करो. हज़ारों लोग वही error पहले सुलझा चुके हैं.