← Back to Chapters

Python Error Handling

? Python Error Handling

⚡ Quick Overview

Error handling in Python is a way to gracefully manage exceptions (errors) that occur during program execution so that your program does not crash unexpectedly. Instead of stopping the program, you can catch errors, show user-friendly messages, and optionally recover from the problem.

? Key Concepts

  • Exception: An error that occurs during program execution (e.g., dividing by zero, invalid input).
  • try block: Wraps code that may raise an exception.
  • except block: Handles the exception if it occurs.
  • Multiple except: Different handlers for different error types.
  • else block: Runs only if no exception occurs in the try block.
  • finally block: Always runs (used for cleanup like closing files).
  • raise: Manually trigger an exception when a condition is not met.

? Syntax and Theory

The general structure of error handling in Python uses try, except, else, and finally blocks:

? View General Syntax
try:
    # code that might raise an exception
    risky_operation()
except SpecificErrorType:
    # handle a specific error
    handle_error()
except AnotherErrorType:
    # handle another error
    handle_another_error()
else:
    # runs only if no exception was raised
    run_if_no_error()
finally:
    # always runs (cleanup)
    cleanup()

? Code Examples

⚠️ Basic try and except

Use try to wrap code that may raise an exception and except to handle it.

? View Code Example
try:
    # attempt a division operation
    x = 10 / 0
except ZeroDivisionError:
    # handle division by zero gracefully
    print("Cannot divide by zero!")

? Handling Multiple Exceptions

You can catch multiple types of errors in separate except blocks.

? View Code Example
try:
    # convert string to integer
    num = int("abc")
    # perform division with the converted number
    result = 10 / num
except ValueError:
    # handle invalid integer conversion
    print("Invalid conversion to integer")
except ZeroDivisionError:
    # handle division by zero
    print("Division by zero error")

? Generic Exception Handling

Catch any exception using except Exception as e and get the error message. Use this carefully, because it can hide specific bugs if overused.

? View Code Example
try:
    # code that may raise any kind of exception
    x = 10 / 0
except Exception as e:
    # catch all exceptions and print the message
    print("Error occurred:", e)

? Using else and finally

else runs if no exception occurs; finally always runs, whether an error occurred or not.

? View Code Example
try:
    # try to divide two numbers
    num = 10 / 2
except ZeroDivisionError:
    # handle division by zero
    print("Error!")
else:
    # runs only if no exception occurred
    print("Division successful")
finally:
    # code that always runs
    print("This always runs")

? Raising Exceptions Manually

You can raise exceptions manually using raise when a condition is not satisfied.

? View Code Example
def check_age(age):
    # validate that age meets minimum requirement
    if age < 18:
        # raise an error if age is too low
        raise ValueError("Age must be 18 or older")
    # return True when age is valid
    return True

try:
    # call the validation function with an invalid age
    check_age(15)
except ValueError as e:
    # handle the validation error
    print("Error:", e)

? Live Output and Explanation

? What do these examples print?

  • Basic division example: Prints Cannot divide by zero! because dividing by zero raises ZeroDivisionError.
  • Multiple exceptions example:
    • int("abc") raises ValueError → prints Invalid conversion to integer.
  • Generic exception example:
    • Again, dividing by zero raises an error, so it prints something like Error occurred: division by zero.
  • else and finally example:
    • No error occurs, so output is: Division successful then This always runs.
  • Custom age check example:
    • check_age(15) raises ValueError → prints Error: Age must be 18 or older.

? Common Error Types

  • ZeroDivisionError: Division by zero.
  • ValueError: Invalid value for conversion or operation.
  • TypeError: Invalid operation between incompatible data types.
  • FileNotFoundError: File you are trying to access does not exist.
  • IndexError: Accessing a list/tuple index that does not exist.
  • KeyError: Accessing a dictionary key that does not exist.

? Use Cases and When to Use

  • Validating user input (e.g., converting strings to numbers safely).
  • Working with files that may or may not exist.
  • Handling network errors (timeouts, connection issues).
  • Protecting critical sections of code from unexpected crashes.
  • Enforcing business rules using custom exceptions.

✅ Tips and Best Practices

  • Always handle specific exceptions (like ValueError, ZeroDivisionError) rather than using a bare except:.
  • Keep the try block as small as possible so it is easy to locate the source of an error.
  • Use finally for code that must run (e.g., closing files or releasing resources).
  • Use raise to enforce conditions and signal invalid states in your code.
  • Avoid catching Exception unless you really need a global handler (and still log the error).

? Practice Tasks

  • Write a program that divides two numbers and handles division by zero using try-except.
  • Convert a string to an integer safely using try-except and print a message if the conversion fails.
  • Raise a custom ValueError when a user enters a negative age or marks.
  • Use multiple except blocks to handle both ValueError and ZeroDivisionError in one program.
  • Open a file inside a try block and use finally to ensure the file is closed.