How do you handle exceptions in Python

In Python, exceptions are handled using a try-except block to gracefully manage errors and prevent program crashes. Here’s how it works:

Basic Syntax:

python

try:
    # Code that might raise an exception
    result = 10 / 0  # Division by zero (will raise ZeroDivisionError)
except ZeroDivisionError:
    # Code to handle the exception
    print("Cannot divide by zero!")


Key Components:

  1. try block:

    • Contains the code that might raise an exception.

    • If an exception occurs, the rest of the try block is skipped.

  2. except block:

    • Catches and handles specific exceptions (e.g., ValueErrorTypeError).

    • You can catch multiple exceptions or use a generic Exception.

  3. else block (optional):

    • Runs only if no exceptions occur in the try block.

  4. finally block (optional):

    • Always executes, whether an exception occurred or not (e.g., for cleanup like closing files).

Example with All Blocks:

python
try:
    num = int(input("Enter a number: "))  # Possible ValueError
    result = 10 / num                    # Possible ZeroDivisionError
except ValueError:
    print("Invalid input! Please enter a number.")
except ZeroDivisionError:
    print("Cannot divide by zero!")
else:
    print(f"Result: {result}")  # Runs if no exception
finally:
    print("Execution complete.")  # Always runs


Common Practices:

  1. Catch specific exceptions (avoid bare except:):

    python
    except (ValueError, TypeError) as e:  # Catch multiple exceptions
        print(f"Error: {e}")
  2. Get the exception details:

    python
    except Exception as e:
        print(f"An error occurred: {e}")
  3. Raise custom exceptions:

    python
    if x < 0:
        raise ValueError("Negative values are not allowed!")
  4. Use finally for resource cleanup:

    python
    file = open("example.txt", "r")
    try:
        content = file.read()
    finally:
        file.close()  # Ensures the file is always closed


Built-in Exceptions (Common Ones):

  • ValueError: Invalid value (e.g., int("abc")).

  • TypeError: Incorrect type (e.g., "hello" + 5).

  • IndexError: List index out of range.

  • KeyError: Dictionary key not found.

  • FileNotFoundError: File does not exist.

Why Use Exception Handling?

  • Prevents abrupt program termination.

  • Improves debugging with meaningful error messages.

  • Ensures resources are released properly (e.g., files, connections)

To Top