首页 > Python资料 博客日记
Python处理多种内置异常范例代码2
2024-10-14 00:00:08Python资料围观13次
这篇文章介绍了Python处理多种内置异常范例代码2,分享给大家做个参考,收藏Python资料网收获更多编程知识
在这个新的示例中,我们将处理一些其他的内置异常,例如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 (通常用于终止程序) 时触发。
在这个示例中,我们通过适当的异常处理提供了更健壮的用户交互,确保程序可以优雅地处理错误和用户的中断请求。这样的做法有助于提升程序的用户体验和可靠性。
版权声明:本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:jacktools123@163.com进行投诉反馈,一经查实,立即删除!
标签:
相关文章
最新发布
- Python: 深入理解 subprocess.run() 执行命令、检查状态与结果处理
- Python 列表全方位解析:创建、操作、删除与遍历的全面指南
- Python 安卓应用构建教程:使用 Kivy 和 AndroidStudio(一)
- Python中类(class)的使用方法
- 【已解决】com.alibaba.excel.exception.ExcelGenerateException: java.lang.InternalError: java.lang.reflect.
- 097、Python 获取文件夹下的所有文件的方法
- 【Python知行篇】代码的曼妙乐章:探索数据与逻辑的和谐之舞
- 将NC栅格表示时间维度的数据提取出来的方法
- 如何使用 matplotlib 在 Python 3 中绘制数据
- mysql操作线上数据要有备份和恢复
点击排行
- 版本匹配指南:Numpy版本和Python版本的对应关系
- 版本匹配指南:PyTorch版本、torchvision 版本和Python版本的对应关系
- Python 可视化 web 神器:streamlit、Gradio、dash、nicegui;低代码 Python Web 框架:PyWebIO
- 相关性分析——Pearson相关系数+热力图(附data和Python完整代码)
- Python与PyTorch的版本对应
- Anaconda版本和Python版本对应关系(持续更新...)
- Python pyinstaller打包exe最完整教程
- Could not build wheels for llama-cpp-python, which is required to install pyproject.toml-based proj