# Goal: Handle errors gracefully
# Topics:
# • try-except blocks
# • Common exceptions (ValueError, FileNotFoundError)
# • finally clause
# • Basic debugging with print statements
# ── 1. Basic try-except ───────────────────────────────────────────────────────
try:
x = int("abc") # raises ValueError
except ValueError:
print("Cannot convert 'abc' to int.") # Cannot convert 'abc' to int.
# ── 2. ValueError ─────────────────────────────────────────────────────────────
def get_age(value):
try:
age = int(value)
print(f"Age is {age}.") # Age is 25. (if valid)
except ValueError:
print(f"'{value}' is not a valid age.") # 'twenty' is not a valid age.
get_age("25") # Age is 25.
get_age("twenty") # 'twenty' is not a valid age.
# ── 3. FileNotFoundError ──────────────────────────────────────────────────────
try:
with open("missing.txt", "r") as f: # file does not exist
content = f.read()
except FileNotFoundError:
print("File not found. Check the filename.") # File not found. Check the filename.
# ── 4. Multiple except Clauses ────────────────────────────────────────────────
def divide(a, b):
try:
result = a / b
print(f"{a} / {b} = {result}") # 10 / 2 = 5.0
except ZeroDivisionError:
print("Cannot divide by zero.") # Cannot divide by zero.
except TypeError:
print("Both values must be numbers.") # Both values must be numbers.
divide(10, 2) # 10 / 2 = 5.0
divide(10, 0) # Cannot divide by zero.
divide(10, "a") # Both values must be numbers.
# ── 5. finally Clause ─────────────────────────────────────────────────────────
# finally always runs — whether an exception occurred or not
def read_file(filename):
try:
f = open(filename, "r")
print(f.read()) # prints file content if found
except FileNotFoundError:
print(f"'{filename}' not found.") # 'data.txt' not found.
finally:
print("Attempted file operation.") # always prints
read_file("data.txt")
# 'data.txt' not found.
# Attempted file operation.
# ── 6. else Clause ────────────────────────────────────────────────────────────
# else runs only if NO exception was raised
try:
num = int("99") # succeeds
except ValueError:
print("Conversion failed.")
else:
print(f"Conversion succeeded: {num}") # Conversion succeeded: 99
# ── 7. Basic Debugging with print ────────────────────────────────────────────
def calculate_discount(price, discount):
print(f"[DEBUG] price={price}, discount={discount}") # [DEBUG] price=200, discount=0.1
try:
result = price - (price * discount)
print(f"[DEBUG] result={result}") # [DEBUG] result=180.0
return result
except TypeError as e:
print(f"[ERROR] {e}") # [ERROR] unsupported operand...
return None
final = calculate_discount(200, 0.1)
print(f"Final price: {final}") # Final price: 180.0
calculate_discount(200, "ten") # [ERROR] unsupported operand type(s)...
# ── 8. Mini Project: Safe Number Input ───────────────────────────────────────
print("\n--- Safe Number Input ---")
def get_number(prompt):
while True:
try:
value = float(input(prompt)) # raises ValueError if not a number
return value
except ValueError:
print("Invalid input. Please enter a number.") # Invalid input. Please enter a number.
a = get_number("Enter first number : ")
b = get_number("Enter second number: ")
try:
print(f"\n{a} / {b} = {a / b:.4f}") # e.g. 10.0 / 4.0 = 2.5000
except ZeroDivisionError:
print("Cannot divide by zero.") # Cannot divide by zero.
finally:
print("Done.") # Done. (always prints)
No comments:
Post a Comment
Please comment below to feedback or ask questions.