Sobes.tech
Junior

What exception handling constructs exist in Python?

sobes.tech AI

Answer from AI

In Python, the following constructs are used for exception handling:

  • try...except: The core of exception handling. The try block contains code that may raise an exception. If an exception occurs, the corresponding except block is executed.

    # Examples of using try...except
    try:
        result = 10 / 0  # Attempt to divide by zero
    except ZeroDivisionError:
        print("Error: Division by zero!")
    
  • except Exception as e: Catches any exception and assigns it to the object e for further processing (such as logging or displaying a message).

    # Catching any exception
    try:
        value = int("abc")
    except Exception as e:
        print(f"An error occurred: {e}")
    
  • Multiple except blocks: Allow handling different types of exceptions differently.

    # Handling multiple exception types
    try:
        file = open("non_existent_file.txt", "r")
        content = file.read()
        file.close()
    except FileNotFoundError:
        print("Error: File not found!")
    except IOError:
        print("Input/output error!")
    
  • except (...): Combining multiple exception types in one block.

    # Combining exception types
    try:
        some_operation()
    except (ValueError, TypeError):
        print("Value or type error!")
    
  • try...except...else: The else block executes if no exceptions occur in the try block.

    # Using else
    try:
        num1 = 10
        num2 = 2
        result = num1 / num2
    except ZeroDivisionError:
        print("Error: Division by zero!")
    else:
        print(f"Division result: {result}")
    
  • try...except...finally: The finally block always executes, regardless of whether an exception occurred or not. It is used for resource cleanup (e.g., closing files).

    # Using finally
    file = None
    try:
        file = open("data.txt", "r")
        content = file.read()
    except FileNotFoundError:
        print("File not found.")
    finally:
        if file:
            file.close()
            print("File closed.")
    
  • raise: Allows explicitly raising an exception.

    # Explicitly raising an exception
    def validate_age(age):
        if age < 0:
            raise ValueError("Age cannot be negative!")
        return age
    
    try:
        validate_age(-5)
    except ValueError as e:
        print(f"Validation error: {e}")
    
What exception handling constructs exist in Python… - sobes.tech