DAY 25 异常处理

目录

      • DAY 25 异常处理
        • 1.异常处理机制
        • 2.debug过程中的各类报错
        • 3.try-except机制
        • 4.try-except-else-finally机制
        • 作业:理解今日的内容即可,可以检查自己过去借助ai写的代码是否带有try-except机制,以后可以尝试采用这类写法增加代码健壮性。

DAY 25 异常处理

1.异常处理机制
2.debug过程中的各类报错
def my_function()print('Hello')
  Cell In[1], line 1def my_function()^
SyntaxError: invalid syntax
x = 5 +print(x)
  Cell In[2], line 1x = 5 +^
SyntaxError: invalid syntax
print(some_undefined_variable)
---------------------------------------------------------------------------NameError                                 Traceback (most recent call last)Cell In[3], line 1
----> 1 print(some_undefined_variable)NameError: name 'some_undefined_variable' is not defined
print(my_lisst)
---------------------------------------------------------------------------NameError                                 Traceback (most recent call last)Cell In[4], line 1
----> 1 print(my_lisst)NameError: name 'my_lisst' is not defined
print('Age: ' + 25)my_number = 10
my_number()
---------------------------------------------------------------------------TypeError                                 Traceback (most recent call last)Cell In[5], line 1
----> 1 print('Age: ' + 25)3 my_number = 104 my_number()TypeError: can only concatenate str (not "int") to str
my_string = '12.34.56'
number = float(my_string)
---------------------------------------------------------------------------ValueError                                Traceback (most recent call last)Cell In[6], line 21 my_string = '12.34.56'
----> 2 number = float(my_string)ValueError: could not convert string to float: '12.34.56'
data = ('apple', 'banana')print(data[2])
---------------------------------------------------------------------------IndexError                                Traceback (most recent call last)Cell In[7], line 31 data = ('apple', 'banana')
----> 3 print(data[2])IndexError: tuple index out of range
student_grades = {'math': 90, 'science': 85}print(student_grades['history'])
---------------------------------------------------------------------------KeyError                                  Traceback (most recent call last)Cell In[8], line 31 student_grades = {'math': 90, 'science': 85}
----> 3 print(student_grades['history'])KeyError: 'history'
a_string = 'hello'print(a_string.length)
---------------------------------------------------------------------------AttributeError                            Traceback (most recent call last)Cell In[9], line 31 a_string = 'hello'
----> 3 print(a_string.length)AttributeError: 'str' object has no attribute 'length'
import numpy as nparr = np.array([1, 2, 3])print(arr.non_existent_attribute)
---------------------------------------------------------------------------AttributeError                            Traceback (most recent call last)Cell In[10], line 51 import numpy as np3 arr = np.array([1, 2, 3])
----> 5 print(arr.non_existent_attribute)AttributeError: 'numpy.ndarray' object has no attribute 'non_existent_attribute'
result = 10 / 0result
---------------------------------------------------------------------------ZeroDivisionError                         Traceback (most recent call last)Cell In[11], line 1
----> 1 result = 10 / 03 resultZeroDivisionError: division by zero
import pandas as pddata = pd.read_csv('hh.csv')
---------------------------------------------------------------------------FileNotFoundError                         Traceback (most recent call last)Cell In[12], line 31 import pandas as pd
----> 3 data = pd.read_csv('hh.csv')File c:\Users\36352\.conda\envs\kk\lib\site-packages\pandas\io\parsers\readers.py:1026, in read_csv(filepath_or_buffer, sep, delimiter, header, names, index_col, usecols, dtype, engine, converters, true_values, false_values, skipinitialspace, skiprows, skipfooter, nrows, na_values, keep_default_na, na_filter, verbose, skip_blank_lines, parse_dates, infer_datetime_format, keep_date_col, date_parser, date_format, dayfirst, cache_dates, iterator, chunksize, compression, thousands, decimal, lineterminator, quotechar, quoting, doublequote, escapechar, comment, encoding, encoding_errors, dialect, on_bad_lines, delim_whitespace, low_memory, memory_map, float_precision, storage_options, dtype_backend)1013 kwds_defaults = _refine_defaults_read(1014     dialect,1015     delimiter,(...)1022     dtype_backend=dtype_backend,1023 )1024 kwds.update(kwds_defaults)
-> 1026 return _read(filepath_or_buffer, kwds)File c:\Users\36352\.conda\envs\kk\lib\site-packages\pandas\io\parsers\readers.py:620, in _read(filepath_or_buffer, kwds)617 _validate_names(kwds.get("names", None))619 # Create the parser.
--> 620 parser = TextFileReader(filepath_or_buffer, **kwds)622 if chunksize or iterator:623     return parserFile c:\Users\36352\.conda\envs\kk\lib\site-packages\pandas\io\parsers\readers.py:1620, in TextFileReader.__init__(self, f, engine, **kwds)1617     self.options["has_index_names"] = kwds["has_index_names"]1619 self.handles: IOHandles | None = None
-> 1620 self._engine = self._make_engine(f, self.engine)File c:\Users\36352\.conda\envs\kk\lib\site-packages\pandas\io\parsers\readers.py:1880, in TextFileReader._make_engine(self, f, engine)1878     if "b" not in mode:1879         mode += "b"
-> 1880 self.handles = get_handle(1881     f,1882     mode,1883     encoding=self.options.get("encoding", None),1884     compression=self.options.get("compression", None),1885     memory_map=self.options.get("memory_map", False),1886     is_text=is_text,1887     errors=self.options.get("encoding_errors", "strict"),1888     storage_options=self.options.get("storage_options", None),1889 )1890 assert self.handles is not None1891 f = self.handles.handleFile c:\Users\36352\.conda\envs\kk\lib\site-packages\pandas\io\common.py:873, in get_handle(path_or_buf, mode, encoding, compression, memory_map, is_text, errors, storage_options)868 elif isinstance(handle, str):869     # Check whether the filename is to be opened in binary mode.870     # Binary mode does not support 'encoding' and 'newline'.871     if ioargs.encoding and "b" not in ioargs.mode:872         # Encoding
--> 873         handle = open(874             handle,875             ioargs.mode,876             encoding=ioargs.encoding,877             errors=errors,878             newline="",879         )880     else:881         # Binary mode882         handle = open(handle, ioargs.mode)FileNotFoundError: [Errno 2] No such file or directory: 'hh.csv'
import hhh
---------------------------------------------------------------------------ModuleNotFoundError                       Traceback (most recent call last)Cell In[13], line 1
----> 1 import hhhModuleNotFoundError: No module named 'hhh'
3.try-except机制
numerator = 10
denominator = 0
result = numerator / denominatorprint(f'结果是: {result}')
print('这行代码不会执行,因为程序已崩溃')
---------------------------------------------------------------------------ZeroDivisionError                         Traceback (most recent call last)Cell In[14], line 31 numerator = 102 denominator = 0
----> 3 result = numerator / denominator5 print(f'结果是: {result}')6 print('这行代码不会执行,因为程序已崩溃')ZeroDivisionError: division by zero
print('使用 try-except 捕获 ZeroDivisionError')numerator = 10
denominator = 0try:print('尝试进行除法运算...')result = numerator / denominatorprint(f'计算结果是: {result}')
except ZeroDivisionError:print('发生了一个除以零的错误!')result = '未定义 (除以零)'print(f'程序继续执行, 最终结果的记录为: {result}')
使用 try-except 捕获 ZeroDivisionError
尝试进行除法运算...
发生了一个除以零的错误!
程序继续执行, 最终结果的记录为: 未定义 (除以零)
x = 'hello'
y = 5
result = x + yprint(result)
---------------------------------------------------------------------------TypeError                                 Traceback (most recent call last)Cell In[16], line 31 x = 'hello'2 y = 5
----> 3 result = x + y5 print(result)TypeError: can only concatenate str (not "int") to str
print('使用 try-except 捕获 TypeError')x = 'Total items: '
y = 5try:print('尝试连接字符串和数字...')message = x + yprint(f'最终消息: {message}')
except TypeError:print('类型错误!不能直接将字符串和数字相加。')print('尝试将数字转换为字符串进行连接...')message = x + str(y)print(f'修正后的消息: {message}')print(f'程序继续, 生成的消息是: {message}')
使用 try-except 捕获 TypeError
尝试连接字符串和数字...
类型错误!不能直接将字符串和数字相加。
尝试将数字转换为字符串进行连接...
修正后的消息: Total items: 5
程序继续, 生成的消息是: Total items: 5
4.try-except-else-finally机制
print('try-except-else 示例')def safe_divide(a, b):print(f'\n尝试计算 {a} / {b}')try:result = a / bexcept ZeroDivisionError:print('错误:除数不能为零!')return Noneexcept TypeError:print('错误:输入必须是数字!')return Noneelse:print('除法运算成功!')print(f'结果是: {result}')print(f'结果的两倍是: {result * 2}')return resultsafe_divide(10, 2)
safe_divide(10, 0)
safe_divide('10', 2)
safe_divide(20, 'abc')
try-except-else 示例尝试计算 10 / 2
除法运算成功!
结果是: 5.0
结果的两倍是: 10.0尝试计算 10 / 0
错误:除数不能为零!尝试计算 10 / 2
错误:输入必须是数字!尝试计算 20 / abc
错误:输入必须是数字!
作业:理解今日的内容即可,可以检查自己过去借助ai写的代码是否带有try-except机制,以后可以尝试采用这类写法增加代码健壮性。

@浙大疏锦行

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:http://www.tpcf.cn/bicheng/84192.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

几何绘图与三角函数计算应用

几何绘图与三角函数计算应用 设计思路 左侧为绘图控制面板,右侧为绘图区域支持绘制点、线、矩形、圆、多边形等基本几何图形实现三角函数计算器(正弦、余弦、正切等)包含角度/弧度切换和常用数学常数历史记录功能保存用户绘图 完整实现代码…

CSS 定位:原理 + 场景 + 示例全解析

一. 什么是CSS定位? CSS中的position属性用于设置元素的定位方式,它决定了元素在页面中的"定位行为" 为什么需要定位? 常规布局(如 display: block)适用于主结构 定位适用于浮动按钮,弹出层,粘性标题等场景帮助我们精确控制元素在页面中的位置 二. 定位类型全…

GESP 二级复习参考 A

本教程完整包含: 5000字详细知识点解析 36个Python/C双语言示例 15个GESP真题及模拟题 8张专业图表和流程图 # C编程二级标准终极教程## 一、计算机存储系统深度解析### 1.1 存储体系架构 mermaid graph TDA[CPU寄存器] --> B[L1缓存 1-2ns]B --> C[L2缓…

嵌入式面试常问问题

以下内容面向嵌入式/系统方向的初学者与面试备考者,全面梳理了以下几大板块,并在每个板块末尾列出常见的面试问答思路,帮助你既能夯实基础,又能应对面试挑战。 一、TCP/IP 协议 1.1 TCP/IP 五层模型概述 链路层(Link Layer) 包括网卡驱动、以太网、Wi‑Fi、PPP 等。负责…

【人工智能 | 项目开发】Python Flask实现本地AI大模型可视化界面

文末获取项目源码。 文章目录 项目背景项目结构app.py(后端服务)index.html(前端界面)项目运行项目图示项目源码项目背景 随着人工智能技术的快速发展,大语言模型在智能交互领域展现出巨大潜力。本项目基于 Qwen3-1.7B 模型,搭建一个轻量化的智能聊天助手,旨在为用户提…

【设计模式】1.简单工厂、工厂、抽象工厂模式

every blog every motto: You can do more than you think. https://blog.csdn.net/weixin_39190382?typeblog 0. 前言 以下是 简单工厂模式、工厂方法模式 和 抽象工厂模式 的 Python 实现与对比,结合代码示例和实际应用场景说明: 1. 简单工厂模式&a…

浏览器访问 AWS ECS 上部署的 Docker 容器(监听 80 端口)

✅ 一、ECS 服务配置 Dockerfile 确保监听 80 端口 EXPOSE 80 CMD ["nginx", "-g", "daemon off;"]或 EXPOSE 80 CMD ["python3", "-m", "http.server", "80"]任务定义(Task Definition&…

01.SQL语言概述

SQL 语言概述 SQL (Structured Query Language)结构化査询语言 1. 关系型数据库的常见组件 数据库: database 表的集合,物理上表现为一个目录表: table,行: row 列: column索引: index视图: view,虚拟的表存储过程:…

C++学习-入门到精通【14】标准库算法

C学习-入门到精通【14】标准库算法 目录 C学习-入门到精通【14】标准库算法一、对迭代器的最低要求迭代器无效 二、算法1.fill、fill_n、generate和generate_n2.equal、mismatch和lexicographical_compare3.remove、remove_if、remove_copy和remove_copy_if4.replace、replace_…

Vue 项目实战:三种方式实现列表→详情页表单数据保留与恢复

背景:在Vue项目中,实现列表页跳转详情页并保留表单数据,返回时恢复表单状态。 核心功能: 保存缓存:点击查询按钮时,表单数据保存恢复缓存:从详情页返回时,恢复表单数据清除缓存&…

iptables实验

实验一:搭建web服务,设置任何人能够通过80端口访问。 1.下载并启用httpd服务器 dnf -y install httpd 开启httpd服务器 systemctl start httpd 查看是否启用 下载并启用iptables,并关闭firewalld yum install iptable…

Razor编程RenderXXX相关方法大全

文章目录 第一章:RenderXXX方法概述1.1 RenderXXX方法的作用与意义1.2 基本工作原理1.3 主要方法分类 第二章:部分视图渲染方法2.1 Html.RenderPartial()2.2 Html.RenderAction()2.3 性能对比分析 第三章:视图组件渲染方法3.1 Html.RenderCom…

Go 语言 range 关键字全面解析

Go 语言 range 关键字全面解析 range 是 Go 语言中用于迭代数据结构的关键字,支持多种数据类型的遍历操作。它提供了一种简洁、安全且高效的方式来处理集合类型的数据。 基本语法 for index, value : range collection {// 循环体 } 1. 数组/切片迭代 fruits :…

美化显示LLDB调试的数据结构

前面的博文美化显示GDB调试的数据结构介绍了如何美化显示GDB中调试的数据结构,本文将还是以mupdf库为例介绍如何美化显示LLDB中调试的数据结构。 先看一下美化后的效果: 一、加载自定义脚本 与GDB类似,需要添加一个~/.lldbinit文件&#xf…

【Java学习笔记】日期类

日期类 第一代日期类:Date 引入包 import java.text.ParseException:日期转换可能会抛出转换异常 import java.text.SimpleDateFormat import java.util.Date 1. 基本介绍 Date:精确到毫秒,代表特定的瞬间 SimpleDateForma…

C++基础进阶:函数、内联函数与Lambda函数详解

引言 在C编程的旅程中,函数是构建复杂程序的基本单元。它们像乐高积木一样,允许我们将代码分解成更小、更易于管理的部分。今天,我们将深入探讨C中的三种重要函数类型:普通函数、内联函数以及Lambda函数。掌握它们,将…

从Node.js到React/Vue3:流式输出技术的全栈实现指南

本文将从底层原理到工程实践,完整解析如何使用Node.js后端结合React和Vue3前端实现流式输出功能,涵盖协议选择、性能优化、错误处理等关键细节,并通过真实场景案例演示完整开发流程。 一、流式输出的核心原理与协议选择 1.1 流式传输的底层机…

AT2401C中科微2.4g芯片PA

作为无线通信系统的核心模块,射频前端芯片通过整合功率放大器(PA)、滤波器、开关和低噪声放大器(LNA)等关键组件,成为保障通信质量、降低功耗及维持信号稳定的决定性因素。 AT2401C是一款面向2.4GHz无线通信…

Linux安装jdk、tomcat

1、安装jdk sudo yum install -y java-1.8.0-openjdk-devel碰到的问题:/var/run/yum.pid 已被锁定 Another app is currently holding the yum lock; waiting for it to exit… https://blog.csdn.net/u013669912/article/details/131259156 参考&#…

在本地电脑中部署阿里 Qwen3 大模型及连接到 Elasticsearch

在今天的文章中,我将参考文章 “使用 Elastic 和 LM Studio 的 Herding Llama 3.1” 来部署 Qwen3 大模型。据测评,这是一个非常不错的大模型。我们今天尝试使用 LM Studio 来对它进行部署,并详细描述如何结合 Elasticsearch 来对它进行使用。…