在这个新的示例中,我们将处理一些其他的内置异常,例如AttributeError
、IndexError
、SyntaxError
(虽然通常在运行时不会被捕获,但我们可以构建一个示例)和KeyboardInterrupt
。我们将创建一个简单的交互式程序,该程序包含对列表操作和属性访问,同时能够正确地处理用户的中断请求。
示例代码
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 - 通常在运行时不被捕获,因为它是在解释阶段抛出的
# eval('if True print("Hello")') # 故意的语法错误
# 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()
异常处理解释:
AttributeError
:尝试访问对象的不存在的属性时触发。IndexError
:尝试访问列表的不存在的索引时触发。SyntaxError
:虽然通常在代码编译阶段就被捕获,但在使用eval()
或exec()
执行动态代码时可能在运行时捕获。KeyboardInterrupt
:当用户在程序运行时按下CTRL+C (通常用于终止程序) 时触发。
在这个示例中,我们通过适当的异常处理提供了更健壮的用户交互,确保程序可以优雅地处理错误和用户的中断请求。这样的做法有助于提升程序的用户体验和可靠性。