← Back to File Operations & Error Handling
Module 5Lesson 440 minutes

Exception Handling

Exception Handling

Handle errors gracefully to prevent program crashes.

Try-Except Basics

try: number = int(input("Enter number: ")) result = 10 / number print(result) except: print("An error occurred!")

Specific Exceptions

try: number = int(input("Enter number: ")) result = 10 / number except ValueError: print("Invalid number!") except ZeroDivisionError: print("Cannot divide by zero!") except Exception as e: print(f"Error: {e}")

Try-Except-Else-Finally

try: file = open('data.txt', 'r') content = file.read() except FileNotFoundError: print("File not found!") else: print("File read successfully!") print(content) finally: print("Closing file...") try: file.close() except: pass

Raising Exceptions

def divide(a, b): if b == 0: raise ValueError("Cannot divide by zero!") return a / b try: result = divide(10, 0) except ValueError as e: print(e)

Common Exceptions

ExceptionWhen It Occurs
ValueErrorInvalid value
TypeErrorWrong type
KeyErrorMissing dict key
IndexErrorInvalid list index
FileNotFoundErrorFile doesn't exist
ZeroDivisionErrorDivision by zero

Practice Exercises

  1. Handle file reading errors
  2. Validate user input with exceptions
  3. Create custom exceptions
  4. Use try-except with loops
  5. Build robust error handling

Next Lesson: Debugging