🛡️ Error Handling

Error handling is crucial for building robust Python applications. Python provides powerful tools to catch, handle, and recover from errors gracefully, preventing crashes and providing meaningful feedback to users.

# Basic error handling
try:
    result = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero!")
    result = 0

print(f"Result: {result}")

# Multiple exception types
try:
    number = int("abc")
except ValueError:
    print("Invalid number format")
except Exception as e:
    print(f"Unexpected error: {e}")

🎯 Why Error Handling Matters

Proper error handling helps you:

  • Prevent Crashes 💥: Keep applications running
  • User Experience 😊: Provide helpful error messages
  • Debugging 🔍: Identify and fix issues quickly
  • Data Safety 🔒: Protect against corruption
  • Maintenance 🔧: Build reliable, maintainable code

📚 Error Handling Topics

Master Python's error handling capabilities:

📊 Exception Reference Tables

Common Built-in Exceptions

ExceptionWhen It OccursExample
ValueErrorInvalid value for operationint("abc")
TypeErrorWrong data type"text" + 5
KeyErrorDictionary key not founddict["missing_key"]
IndexErrorList index out of rangelist[100]
FileNotFoundErrorFile doesn't existopen("missing.txt")
ZeroDivisionErrorDivision by zero10 / 0
AttributeErrorObject has no attribute"text".missing_method()
ImportErrorModule import failsimport nonexistent

Exception Handling Patterns

PatternUse CaseExample
Basic try/exceptHandle single exceptionexcept ValueError:
Multiple exceptHandle different errorsexcept (ValueError, TypeError):
Catch allHandle any exceptionexcept Exception:
Exception infoGet error detailsexcept Exception as e:
Finally blockAlways execute cleanupfinally:
Else blockRun if no exceptionselse:

🌟 Quick Examples

Here's what you'll learn to handle:

# File handling with errors
try:
    with open("data.txt", "r") as file:
        content = file.read()
        print("File read successfully")
except FileNotFoundError:
    print("File not found")
except PermissionError:
    print("No permission to read file")

# Data conversion with errors
try:
    user_input = "25"
    age = int(user_input)
    print(f"Age: {age}")
except ValueError:
    print("Please enter a valid number")

# Custom error handling
class CustomError(Exception):
    pass

try:
    raise CustomError("Something went wrong")
except CustomError as e:
    print(f"Custom error: {e}")

🏗️ Error Handling Hierarchy

Understanding Python's exception hierarchy helps you catch errors effectively:

BaseException
 +-- Exception
      +-- ValueError
      +-- TypeError  
      +-- KeyError
      +-- IndexError
      +-- FileNotFoundError
      +-- ZeroDivisionError
      +-- AttributeError
      +-- ImportError

Build robust Python applications that handle errors gracefully! 🛡️✨

Was this helpful?

😔Poor
🙁Fair
😊Good
😄Great
🤩Excellent