DAY 25 异常处理

目录

DAY 25 异常处理

1.异常处理机制
2.debug过程中的各类报错
python 复制代码
def my_function()


print('Hello')
复制代码
  Cell In[1], line 1
    def my_function()
                     ^
SyntaxError: invalid syntax
python 复制代码
x = 5 +

print(x)
复制代码
  Cell In[2], line 1
    x = 5 +
           ^
SyntaxError: invalid syntax
python 复制代码
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
python 复制代码
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
python 复制代码
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
python 复制代码
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'
python 复制代码
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
python 复制代码
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'
python 复制代码
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'
python 复制代码
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'
python 复制代码
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
python 复制代码
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'
python 复制代码
import hhh
复制代码
---------------------------------------------------------------------------

ModuleNotFoundError                       Traceback (most recent call last)

Cell In[13], line 1
----> 1 import hhh


ModuleNotFoundError: No module named 'hhh'
3.try-except机制
python 复制代码
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
python 复制代码
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
尝试进行除法运算...
发生了一个除以零的错误!
程序继续执行, 最终结果的记录为: 未定义 (除以零)
python 复制代码
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
python 复制代码
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机制
python 复制代码
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机制,以后可以尝试采用这类写法增加代码健壮性。

@浙大疏锦行

相关推荐
tanyyinyu8 分钟前
Python列表:高效灵活的数据存储与操作指南
开发语言·windows·python
沐雨潇竹16 分钟前
vs2022中detach qt widgets designer
开发语言·qt
加油搞钱加油搞钱20 分钟前
鹰盾加密器“一机一码”技术全维度剖析:从底层实现到生态防护体系
开发语言·网络·python
朝朝又沐沐23 分钟前
基于算法竞赛的c++编程(28)结构体的进阶应用
开发语言·c++·算法
站大爷IP33 分钟前
Python项目文件组织与PyCharm实践:打造高效开发环境
python
豪斯有话说38 分钟前
C++_红黑树
开发语言·数据结构·c++
莱茵不哈哈38 分钟前
C/C++八股文
开发语言·c++
nbbsn1 小时前
第四十天打卡
python·深度学习·机器学习
ZHOU_WUYI1 小时前
Flask RESTful 示例
python·flask·restful
白玉cfc1 小时前
Objective-C常用命名规范总结
开发语言·ios·objective-c