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 write | It does |
|---|---|
Type: message | the last line of a traceback: what went wrong; the line above says where |
NameError, TypeError, ValueError | an unknown name; the wrong kind of value; the right kind but a bad value |
IndexError, KeyError, ZeroDivisionError | no 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 type | avoid 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 + break | asks 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
try and except
- 152.Python Program to Double a Number with try and exceptEasySolve
- 153.Python Program to Split a Bill SafelyMediumSolve
else and finally
- 154.Python Program to Check Even or Odd with try, except and elseEasySolve
- 155.Python Program to Make a Ticket Machine with finallyMediumSolve
raise
- 156.Python Program to Check an Age with raiseEasySolve
- 157.Python Program to Withdraw Money with raiseMediumSolve
Safe input
- 158.Python Program to Keep Asking for a Valid AgeMediumSolve
- 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.