livepython.net
CHAPTER 17Handling Errors (Exceptions)
17.6  PRACTICE

Python Exception Handling Practice Questions

Chapter 17 Recap and Practice

Your programs can now handle errors instead of crashing. Here is the chapter in one table:

You writeIt does
Type: messagethe last line of a traceback: what went wrong; the line above says where
NameError, TypeError, ValueErroran unknown name; the wrong kind of value; the right kind but a bad value
IndexError, KeyError, ZeroDivisionErrorno such position; no such key; dividing by 0
try:runs the risky lines; on an error, jumps to the matching except
except ValueError:catches only that error type; other errors still stop the program
except (ValueError, ZeroDivisionError):one block for two error types
except ValueError as e:print(e) shows the error's message
except: with no typeavoid it: it hides every error, even typos
else:runs only when the try had no error
finally:runs every time, error or not
raise ValueError("message")makes an error happen on purpose, for a value that makes no sense
while True: + try + breakasks again until the input is valid

And the checklist for safe input: input() and int() inside the loop and inside the try, break only on success, a friendly message in except, and always a named error type.

Practice questions

Use input() with no prompt text. The tests type bad inputs on purpose, like abc, 2.5 or 0, so try those yourself before you submit. Your program should print a friendly message, never crash.

Exceptions and error types

  1. 150.Fix a TypeError in a Birthday MessageEasySolve
  2. 151.Fix a KeyError in a Price LookupMediumSolve

try and except

  1. 152.Python Program to Double a Number with try and exceptEasySolve
  2. 153.Python Program to Split a Bill SafelyMediumSolve

else and finally

  1. 154.Python Program to Check Even or Odd with try, except and elseEasySolve
  2. 155.Python Program to Make a Ticket Machine with finallyMediumSolve

raise

  1. 156.Python Program to Check an Age with raiseEasySolve
  2. 157.Python Program to Withdraw Money with raiseMediumSolve

Safe input

  1. 158.Python Program to Keep Asking for a Valid AgeMediumSolve
  2. 159.Python Program to Make a Safe CalculatorHardSolve

Errors are no longer the end of your program. Next, you'll use Python's ready-made modules, like math and random.