Learning

Exception Handling Basics

Exception Handling Basics

The Problem

python
number = int('hello') # ValueError! result = 10 / 0 # ZeroDivisionError! my_list = [1, 2, 3] print(my_list[10]) # IndexError!

Basic try / except

python
try: result = 10 / 0 except ZeroDivisionError: print('Cannot divide by zero!') # Program continues running instead of crashing!

Catching the Exception Object

python
number = int('abc') except ValueError as e: print(f'Error message: {e}') # 'invalid literal for int()' print(f'Error type: {type(e).__name__}') # 'ValueError'

Multiple except Blocks

python
# 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.

else Block

python
try: result = 10 / 2 except ZeroDivisionError: print('Error') else: print(f'Success! Result: {result}') # This runs

finally Block

python
try: 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!

Best Practice Pattern

python
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')
Key Rules
  • •Always catch SPECIFIC exceptions (like ValueError) — avoid bare 'except:' or 'except Exception' when possible
  • •Order except blocks from most specific to most generic — Python matches top-down
  • •Use 'else' for code that should ONLY run if no exception occurred (keeps try block slim)
  • •Use 'finally' for cleanup that MUST run regardless of success/failure (like closing connections)
  • •Bare 'except:' catches EVERYTHING including KeyboardInterrupt and SystemExit — almost never use it
Your Task

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.

EditorPython · JSX
PreviewUpdates on Run Tests
Loading preview…
Tests
Should define safe_divide function
Should use try/except/else structure
Should catch ZeroDivisionError specifically
Should catch TypeError specifically
Should return tuple format
Should define divide_and_print that calls safe_divide