Information about cookies on this page

Our website uses cookies to ensure the functionality of the website, to collect and analyze information about the performance and usage of the website. Privacy Policy

  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in
  
  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in

Which Error?

except ValueError: catches only a ValueError. Any other exception in the try block still ends the program, with its traceback. That's how it should be: an except is for a problem you expect, such as text that isn't a number, while a mistake you didn't expect should show up, so that you can fix it.

When a try block can fail in more than one way, give it an except for each type of exception:

prizes = {1: "a gold medal", 2: "a silver medal", 3: "a bronze medal"}
place_text = "5"

try:
    place = int(place_text)
    print("You get", prizes[place])
except ValueError:
    print("The place must be a number.")
except KeyError:
    print("Only the first three places get a prize.")
print("Thanks for taking part!")
Only the first three places get a prize.
Thanks for taking part!

The keys of prizes are numbers, which works too. prizes[5] raises a KeyError, so Python looks at the except blocks from the top and runs the first one whose type matches. As with elif, only one of them runs. With place_text = "second", int() raises a ValueError, and the program prints The place must be a number. When two types should be handled the same way, one except can name both, as a tuple: except (ValueError, KeyError):.

You can also write except: without a type. It catches every exception, and that's the trouble: it catches your own mistakes too. Can you spot the one here?

age_text = "14"

try:
    age = int(age_text)
    print("Next year you'll be " + age + 1)
except:
    print("The age must be a number.")
The age must be a number.

The age is "14", a perfectly good number, but the program says it isn't. What really went wrong is a TypeError in the print(): text and a number can't be joined with +. The except: caught it and hid it behind the wrong message. With except ValueError:, the program would end with TypeError: can only concatenate str (not "int") to str and the number of the line, and you'd fix it in a few seconds. So always name the exception you expect.

A SyntaxError in your program can't be caught: with one, nothing runs, not even the try.

Instructions

  1. 1

    The program says the count isn't a number, although count_text is "2". Replace except: with except ValueError: and run the program again: now you see what really went wrong. Fix it. The program then prints 2 x tea: $4.

  2. 2

    Change item to "juice" and run the program: it ends with a KeyError, because the coffee shop doesn't sell juice. Add a second except block, for KeyError, that prints Sorry, we don't have juice. with the name of the item from item. Then change item back to "tea": the exercise also tries your program with other items and counts.

Back

3/10

  1. 1. Reading a Traceback
  2. 2. Catching an Error
  3. 3. Which Error?
  4. 4. Quiz: try and except
  5. 5. The Message of an Error
  6. 6. else and finally
  7. 7. Quiz: else and finally
  8. 8. Raising an Error
  9. 9. Catching Your Own Errors
  10. 10. Summary
Next

Try it yourself

Do this exercise right here in your browser. No account needed.