DAY 25 异常处理
目录
DAY 25 异常处理
1.异常处理机制
2.debug过程中的各类报错
def my_function()
print('Hello')
Cell In[1], line 1
def my_function()
^
SyntaxError: invalid syntax
x = 5 +
print(x)
Cell In[2], line 1
x = 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 = 10
4 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 2
1 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 3
1 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 3
1 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 3
1 a_string = 'hello'
----> 3 print(a_string.length)
AttributeError: 'str' object has no attribute 'length'
import numpy as np
arr = np.array([1, 2, 3])
print(arr.non_existent_attribute)
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
Cell In[10], line 5
1 import numpy as np
3 arr = np.array([1, 2, 3])
----> 5 print(arr.non_existent_attribute)
AttributeError: 'numpy.ndarray' object has no attribute 'non_existent_attribute'
result = 10 / 0
result
---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
Cell In[11], line 1
----> 1 result = 10 / 0
3 result
ZeroDivisionError: division by zero
import pandas as pd
data = pd.read_csv('hh.csv')
---------------------------------------------------------------------------
FileNotFoundError Traceback (most recent call last)
Cell In[12], line 3
1 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 parser
File 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 None
1891 f = self.handles.handle
File 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 mode
882 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 hhh
ModuleNotFoundError: No module named 'hhh'
3.try-except机制
numerator = 10
denominator = 0
result = numerator / denominator
print(f'结果是: {result}')
print('这行代码不会执行,因为程序已崩溃')
---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
Cell In[14], line 3
1 numerator = 10
2 denominator = 0
----> 3 result = numerator / denominator
5 print(f'结果是: {result}')
6 print('这行代码不会执行,因为程序已崩溃')
ZeroDivisionError: division by zero
print('使用 try-except 捕获 ZeroDivisionError')
numerator = 10
denominator = 0
try:
print('尝试进行除法运算...')
result = numerator / denominator
print(f'计算结果是: {result}')
except ZeroDivisionError:
print('发生了一个除以零的错误!')
result = '未定义 (除以零)'
print(f'程序继续执行, 最终结果的记录为: {result}')
使用 try-except 捕获 ZeroDivisionError
尝试进行除法运算...
发生了一个除以零的错误!
程序继续执行, 最终结果的记录为: 未定义 (除以零)
x = 'hello'
y = 5
result = x + y
print(result)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[16], line 3
1 x = 'hello'
2 y = 5
----> 3 result = x + y
5 print(result)
TypeError: can only concatenate str (not "int") to str
print('使用 try-except 捕获 TypeError')
x = 'Total items: '
y = 5
try:
print('尝试连接字符串和数字...')
message = x + y
print(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 / b
except ZeroDivisionError:
print('错误:除数不能为零!')
return None
except TypeError:
print('错误:输入必须是数字!')
return None
else:
print('除法运算成功!')
print(f'结果是: {result}')
print(f'结果的两倍是: {result * 2}')
return result
safe_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机制,以后可以尝试采用这类写法增加代码健壮性。
原文地址:https://blog.csdn.net/HINOTOR_/article/details/148516977
免责声明:本站文章内容转载自网络资源,如侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!