目錄
- 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機制,以后可以嘗試采用這類寫法增加代碼健壯性。
@浙大疏錦行