PythonLesson 13 of 16
Errors and try/except in Python
In Python an error is called an exception: the program stops and tells you what went wrong. try/except lets you catch it and carry on.
Key points
- The last line of a traceback names the error and its cause
- try: holds risky code; except SomeError: says what to do if it fails
- Catch specific errors: ValueError, ZeroDivisionError, KeyError
- finally runs no matter what
- raise ValueError("...") throws an error yourself when data is wrong
Example
try: number = int("abc")except ValueError: print("That is not a number") try: print(10 / 0)except ZeroDivisionError as error: print("Oops:", error)finally: print("Done")Both errors were caught and the program ran to the end. as error gave access to the message, and finally ran either way.
Task
How to use the editor⌘ Enter or Ctrl Enter runs the code, ⇧ ⌘ Enter checks the task.Tab and Shift Tab indent the line or the selection; Esc, then Tab leaves the editor.The check compares what the program printed with the task; spaces at line ends do not matter.After two failed checks you may open the solution. Your code is kept in this browser.Survey answers arrived as text, and not all of them are numbers. Add the ones that convert to a number into total and count the rest in skipped.
Output
What your program prints appears here.