Code inside try: runs normally; if it raises an error, Python jumps to the matching except SomeError: block instead of stopping the program. Catch the specific error you expect: ZeroDivisionError for dividing by zero, ValueError for int("abc"), IndexError for a list position that does not exist, KeyError for a missing dictionary key. A bare except: hides real bugs.
Optional parts: else: runs when no error happened, finally: runs no matter what (closing files). Returning a sensible fallback, like None, from the except block is a common shape for helper functions.
def parse(text):
try:
return float(text)
except ValueError:
return None
print(parse("2.5"), parse("two")) # 2.5 NoneYour task
Write safe_divide(a, b) returning a / b or None when b is zero, read_int(text) returning the integer value of the text or None when it is not one, and first_item(items) returning the first item or None when the list is empty. Use try/except in each.
Hint 1
try: return a / b except ZeroDivisionError: return None
Hint 2
int() raises ValueError; items[0] on an empty list raises IndexError.
Show the solution
def safe_divide(a, b):
try:
return a / b
except ZeroDivisionError:
return None
def read_int(text):
try:
return int(text)
except ValueError:
return None
def first_item(items):
try:
return items[0]
except IndexError:
return None