number = int('hello') # ValueError!
result = 10 / 0 # ZeroDivisionError!
my_list = [1, 2, 3]
print(my_list[10]) # IndexError!try:
result = 10 / 0
except ZeroDivisionError:
print('Cannot divide by zero!')
# Program continues running instead of crashing! number = int('abc')
except ValueError as e:
print(f'Error message: {e}') # 'invalid literal for int()'
print(f'Error type: {type(e).__name__}') # 'ValueError' # Some risky operation
value = int('hello')
except ValueError:
print('Invalid number format')
except ZeroDivisionError:
print('Division failed')
except (TypeError, IndexError) as e:
# Catch multiple types in one block
print(f'Other error: {e}')
except Exception as e:
# Catch-all (use sparingly!)
print(f'Unexpected error: {e}')Order matters: Catch specific exceptions BEFORE generic ones.
try:
result = 10 / 2
except ZeroDivisionError:
print('Error')
else:
print(f'Success! Result: {result}') # This runstry:
f = open('data.txt', 'r')
content = f.read()
except FileNotFoundError:
print('File not found')
finally:
print('Cleanup code runs here')
# f.close() # Be careful: f might not be defined if open() failed!try:
with open('data.txt', 'r') as f:
content = f.read()
except FileNotFoundError:
print('File missing')
else:
print(f'Read {len(content)} chars')
finally:
print('Operation attempted')Create a function `safe_divide(a, b)` that returns a tuple `(success: bool, result_or_error_msg)`. If division works, return `(True, result)`. If `ZeroDivisionError`, return `(False, 'Division by zero')`. If `TypeError`, return `(False, 'Invalid types')`. Use `else` to handle success. Create a wrapper `divide_and_print(a, b)` that calls safe_divide and prints the outcome.