4.1.1.9 - Exceptions and defensive input (Python)
Distinguish exceptions from ordinary invalid data, handle specific failures in Python, and recover without accidentally using an unsuccessful result.
Exceptions and program flow
An exception reports a failure encountered while a program executes. Normal execution leaves the failing operation and searches for a suitable handler. If no handler is found, the program normally stops and reports the exception. Handling an exception allows the program to make a controlled response; it does not retrospectively complete the failed operation.
| Operation | Example failure | Exception |
|---|---|---|
| Convert integer text | int("eight") | ValueError |
| Divide | 12 / 0 | ZeroDivisionError |
| Index a list/string | [4, 6][2] | IndexError |
| Open a missing file | open("missing.txt") | FileNotFoundError |
A syntax error prevents parsing the source; a logical error can produce a wrong result without any exception. age = -3 is valid Python and an integer conversion of "-3" succeeds, but the age may violate the application's rules. Exception handling is therefore different from validation, which checks whether an otherwise representable value is acceptable.
Specific handlers and reliable cleanup
A try block contains operations that might fail, and an except block handles a matching exception. Keep the protected region focused so you can identify what failed. Only the matching handler runs, and remaining statements in the failing try block are skipped.
Separate conversion and division failures
{"code":"text = input()\ntry:\n divisor = int(text)\n quotient = 12 / divisor\nexcept ValueError:\n print("not an integer")\nexcept ZeroDivisionError:\n print("cannot divide by zero")\nelse:\n print(quotient)\nfinally:\n print("finished")\n","instructions":"Predict and run separately with inputs 3, 0 and abc. Explain why quotient is printed only on success and finished is printed in all three cases. Then change the numerator from 12 to 18 and predict/run all three cases again.","files":[],"original_filename":"main.py","runtime_profile":"python-console-v1","file_mode":"fresh"}
With 3, output is 4.0 then finished; with 0, cannot divide by zero then finished; with abc, not an integer then finished. else executes only when the try completes without an exception. finally executes when control leaves this structure, including these success and handled-failure paths; it is useful for releasing resources. Abrupt process termination is outside this ordinary control-flow guarantee.
Continue this lesson.
You’re previewing NovaLearn without an account. Create a free account to read the rest.
Create free account