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.pswp.cn/bicheng/84192.shtml
繁體地址,請注明出處:http://hk.pswp.cn/bicheng/84192.shtml
英文地址,請注明出處:http://en.pswp.cn/bicheng/84192.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋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 來對它進行使用。…