Error Handling

Python FundamentalsExceptionsFree Lesson

Advertisement

Introduction

Python uses exceptions to handle errors gracefully and prevent program crashes.

Try-Except Block

try:
    result = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero!")
except Exception as e:
    print(f"Error: {e}")
else:
    print("No errors occurred")
finally:
    print("This always runs")

Raising Exceptions

def validate_age(age):
    if age < 0:
        raise ValueError("Age cannot be negative")
    if age > 150:
        raise ValueError("Invalid age")
    return True

Custom Exceptions

class InvalidInputError(Exception):
    def __init__(self, message="Invalid input"):
        self.message = message
        super().__init__(self.message)

raise InvalidInputError("Input must be positive")

Common Exceptions

ExceptionDescription
TypeErrorOperation on incompatible types
ValueErrorInvalid value for operation
IndexErrorList index out of range
KeyErrorDictionary key not found
FileNotFoundErrorFile doesn't exist

Practice Problems

  1. Create a safe calculator that handles division by zero
  2. Implement input validation with custom exceptions
  3. Parse user input and handle all possible errors
  4. Create a retry mechanism for failing operations
  5. Build error logging system

Advertisement

Need Expert Python Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement