Errors and try / except
When an error happens at runtime, Python stops the program. try and except let you handle it instead of crashing.
PYTHON
try: qty = int("ten") except ValueError: print("Please enter a number")
| typo (missing bracket or :) | SyntaxError |
| undefined name | NameError |
| wrong type for the operation | TypeError |
| unsuitable value | ValueError |
| list index out of range | IndexError |
| missing dictionary key | KeyError |
| division by zero | ZeroDivisionError |
PYTHON
def safe_divide(a, b): try: return a / b except ZeroDivisionError: return None print(safe_divide(10, 2)) print(safe_divide(10, 0))
PYTHON
prices = {"Laptop": 4800}
try:
print(prices["Phone"])
except KeyError as e:
print("Missing product:", e)
finally:
print("Lookup finished")