Exception Handling and Exit Codes
Exception Handling (try / except)
Catch expected errors so the program doesn't crash.
python
try:
amount = int(user_input) # raises ValueError if "abc" comes in
except ValueError:
print("[Error] Please enter the amount as a number.")
print("[Hint] e.g. 15000")- Requirement: no stack trace output (the scary red error dump); always print "the cause + a hint for fixing it"
Exit Codes
An exit code is the report card a program leaves for the operating system when it finishes.
python
import sys
sys.exit(0) # 0 = normal exit
sys.exit(1) # anything other than 0 = exit due to an error- Requirement: 0 for a normal exit, a non-zero value for an error exit
Summary
| Concept | Summary |
|---|---|
| Exception handling | Don't crash; tell the user the cause + a hint |
| Exit code | 0 for a normal exit, a non-zero value for an error exit |
Source: Codyssey-B1/B2-1
