Python Example for Handling Multiple Built-In Exceptions (Part 2)

Time: Column:Python views:262

In this new example, we handle additional built-in exceptions such as AttributeError, IndexError, and SyntaxError (even though it is typically not caught during runtime). We also demonstrate handling user interruptions with KeyboardInterrupt. The program is an interactive script that includes operations on lists and attribute access while gracefully handling user interruption requests.

Example Code

def main():
    try:
        # AttributeError
        class SimpleClass:
            def __init__(self):
                self.message = "Hello"
        
        obj = SimpleClass()
        print(obj.non_existent_attribute)

        # IndexError
        my_list = [1, 2, 3]
        print("Fourth element is:", my_list[3])

        # SyntaxError - Usually caught during the code interpretation stage
        # eval('if True print("Hello")')  # Intentional syntax error

        # KeyboardInterrupt
        input("Press Enter, or stop the program with CTRL+C to trigger KeyboardInterrupt: ")

    except AttributeError:
        print("Error: Tried to access a non-existent attribute.")
    except IndexError:
        print("Error: List index is out of range.")
    except SyntaxError:
        print("Error: There was a syntax error in your code.")
    except KeyboardInterrupt:
        print("You cancelled the operation.")
    except Exception as e:
        print(f"An unexpected error occurred: {e}")

if __name__ == "__main__":
    main()

Exception Handling Explained

  1. AttributeError
    Triggered when attempting to access a non-existent attribute of an object.

  2. IndexError
    Raised when trying to access a list element with an out-of-range index.

  3. SyntaxError
    Usually detected during code interpretation and not runtime. However, it can be caught if dynamically executed code (via eval() or exec()) contains syntax errors.

  4. KeyboardInterrupt
    Occurs when the user interrupts program execution by pressing CTRL+C during runtime.

  5. General Exception
    Catches any other exceptions that are not specifically handled above, ensuring robust error handling.


Benefits of This Example

This script demonstrates effective error handling for both common programming mistakes and unexpected user actions. By properly handling exceptions, the program:

  • Avoids crashes.

  • Provides meaningful error messages.

  • Ensures a better user experience and enhanced reliability.