Ravindra BagaleCourses & study guides मराठी Track your progress

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

  1. Go to the last line first.
  2. Read the error type (e.g. ValueError).
  3. Read the message after the colon.
  4. Look one line up for the line number in your code.
  5. Fix that line and run again.
1. Look at the LAST line2. Error type: what kind of problem3. Message: what exactly4. Line number: where5. Fix and run again
Reading an error (read from top to bottom)

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.