在执行流程中,根据前述步骤可以描绘出以下序列图: FileSystemFunctionUserFileSystemFunctionUseralt[File exists][File does not exist]open_file("example.txt")open("example.txt")returns file contentprint contentclose fileraise FileNotFoundErrorprint "错误:文件 example.txt 未找到!" 结尾 通过本文的介绍,相...
1,NameError(属于编译时异常) 2,IndexError(属于运行时异常) 3,AttributeError(属于运行时异常) 4,FileNotFoundError(属于运行时异常) 5,ZeroDivisionError(属于运行时异常) 二,捕获异常 三,抛异常 1,raise语句 2,assert语句 四,自定义异常 一,Exception异常 1,NameError(属于编译时异常) 该异常产生的原因是因为...
一、Python 捕获指定类型异常 1、异常类型简介 Python 中的 异常 由 异常类 Exception Class 表示 , 每个异常类都代表一个特定的错误类型 ; 常见的 异常类 : FileNotFoundError...和 处理异常 ; 2、捕获并处理指定异常 在 Python 中 , 可以捕获指定类型的异常 , 语法如下 : try: 可能出现异常...
fromtenacityimportretry, retry_if_exception_type, retry_if_not_exception_type @retry(retry=retry_if_exception_type(FileExistsError)) defdemo_func7(): raiseTimeoutError @retry(retry=retry_if_not_exception_type(FileNotFoundError)) defdemo_func8(): raiseFile...
File "C:/Users/Administrator/Desktop/code/code/read_file.py", line 1, in <module> raise NameError('名称不匹配') NameError: 名称不匹配 常用异常类型 try-finally语句 finally表示不管有没有捕捉到异常,最终都要执行finally代码块 如下: try: number = 10/0 except: print('0无法做除数') finally...
Python 解释器会记录最后一个发生的异常,raise会将最后一个异常抛出。上面代码中的raise相当于raise e。 assert断言 assert语句称为断言,就是判断某个表达式是否为真: 表达式为True时,正常通过 表达式为False时,抛出AssertionError异常 示例如下: 表达式1 == 1为True,没有反应: ...
文件操作:读取不存在的文件时可能会引发FileNotFoundError。 网络请求:网络连接失败时可能会引发ConnectionError。 数据处理:数据格式不正确时可能会引发ValueError。 示例代码 以下是一个简单的异常处理示例: 代码语言:txt 复制 try: # 尝试执行可能引发异常的代码 result = 10 / 0 except ZeroDivisionError as e: #...
| | +-- ConnectionResetError (连接重置错误) | +-- FileExistsError (文件存在的错误) | +-- FileNotFoundError (文件不存在的错误) | +-- InterruptedError (中断的错误) | +-- IsADirectoryError (是一个文件目录的错误) | +-- NotADirectoryError(不是一个文件目录的错误) ...
异常说明: [Errno 2] No such file or directory: 'python.txt' finally 程序正常结束 7.raise主动触发异常 可以使用raise语句自己触发异常,语法如下: raise [Exception [, args [, traceback]]] 语句中 Exception 是异常的类型(例如,IOError )参数标准异常中任一种,args 是自已提供的异常参数。最后一个参数...