In this new example, we handle additional built-in exceptions such as
AttributeError
,IndexError
, andSyntaxError
(even though it is typically not caught during runtime). We also demonstrate handling user interruptions withKeyboardInterrupt
. 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
AttributeError
Triggered when attempting to access a non-existent attribute of an object.IndexError
Raised when trying to access a list element with an out-of-range index.SyntaxError
Usually detected during code interpretation and not runtime. However, it can be caught if dynamically executed code (viaeval()
orexec()
) contains syntax errors.KeyboardInterrupt
Occurs when the user interrupts program execution by pressingCTRL+C
during runtime.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.