资源简介 (共49张PPT)第9章 异常Chap9 ExceptionsThere is a road in the mountains of books, and diligence is the pathpython中的异常9.12程序设计错误3语法错误运行时错误逻辑错误6 = x * 2x = 3 / 0area = 2 * 3.14 * 34异常(Exception)Traceback (most recent call last):File "", line 1, in 1/0ZeroDivisionError: division by zero5>>> 1 / 0SourceTraceback (most recent call last):File "", line 1, in y = x + 1NameError: name 'x' is not defined>>> y = x + 1Source用异常对象(exception object)表示异常情况Python用异常对象(exception object)表示异常情况,遇到错误时如果异常对象没有6异常查看异常类 dir(__builtins__)7类 名 描 述BaseException 所有异常的基类Exception 常规异常的基类AttributeError 对象不存在此属性IndexError 序列中无此索引IOError 输入/输出操作失败KeyboardInterrupt 用户中断执行(通常输入Ctr-C)KeyError 映射中不存在此键NameError 找不到名字(变量)SyntaxError Python 语法错误TypeError 对类型无效的操作ValueError 传入无效的参数ZeroDivisionError 除(或取模)运算的第二个参数为0异常处理if y != 0:print(x / y)else:print('division by zero')8VStry-except异常处理语句可以用if语句判断除数的特殊情况后单独处理,形如:但这种做法不够灵活,有时效率也不高。Python中提供了简单自然的异常处理方法。因为这些实例可以被引发、捕捉,对捕捉到的异常可以进行处理,以免程序因为异常而终止运行。捕捉异常9.29异常Enter the first number: aTraceback (most recent call last):File "C:\Python\programs\exception1.py", line 1, in num1 = int(input('Enter the first number: '))ValueError: invalid literal for int() with base 10: 'a'10# Filename: prog9-1.pynum1 = int(input('Enter the first number: '))num2 = int(input('Enter the second number: '))print(num1 / num2)File9.2.1 try-except语句1112try-except语句13# Filename: prog9-2.pytry:num1 = int(input('Enter the first number: '))num2 = int(input('Enter the second number: '))print(num1 / num2)except ValueError:print('Please input a digit!')Filetry:被检测的语句块except Exception:异常处理语句块14try-except语句15# Filename: prog9-3.pytry:num1 = int(input('Enter the first number: '))num2 = int(input('Enter the second number: '))print(num1 / num2)except ZeroDivisionError:print('The second number cannot be zero!')File169.2.2 多个except子句和一个except块捕捉多个异常17多个except子句18# Filename: prog9-4.pytry:num1 = int(input('Enter the first number: '))num2 = int(input('Enter the second number: '))print(num1 / num2)except ValueError:print('Please input a digit!')except ZeroDivisionError:print('The second number cannot be zero!')File一个except块捕捉多个异常19# Filename: prog9-5.pytry:num1 = int(input('Enter the first number: '))num2 = int(input('Enter the second number: '))print(num1 / num2)except (ValueError, ZeroDivisionError):print('Invalid input!')File空except子句20# Filename: prog9-6.pytry:num1 = int(input('Enter the first number: '))num2 = int(input('Enter the second number: '))print(num1 / num2)except:print('Something went wrong!')File一了百了:except:如果想要捕捉所有的异常,可以使用空的except子句21as子句22# Filename: prog9-7.pytry:num1 = int(input('Enter the first number: '))num2 = int(input('Enter the second number: '))print(num1 / num2)except Exception as err:print('Something went wrong!')print(err)File23as子句24try:被检测的语句块except 异常类名 as 错误原因名:异常处理语句块print(错误原因名)9.2.3 else子句25else子句26# Filename: prog9-8.pytry:num1 = int(input('Enter the first number: '))num2 = int(input('Enter the second number: '))print(num1 / num2)except(ValueError, ZeroDivisionError):print('Invalid input!')else:print('Aha, I am smart.')FileEnter the first number: 3Enter the second number: 50.6Aha, I am smart.如果输入正确没有引发异常,则跳过except执行else子句程序prog9-2~prog9-8 中虽然都做了异常处理,但只有简单的提示信息不能再次输人,如果想要在产生异常后能多次输入直到正确为止,则可以在外层加上while True语句和else子句。27加入循环28# Filename: prog9-9.pywhile True:try:num1 = int(input('Enter the first number: '))num2 = int(input('Enter the second number: '))print(num1 / num2)except ValueError:print('Please input a digit!')except ZeroDivisionError:print('The second number cannot be zero!')else:breakFileEnter the first number: aPlease input a digit!Enter the first number: 3Enter the second number: 0The second number cannot be zero!Enter the first number: 3Enter the second number: 50.629break语句的位置30# Filename: prog9-9’.pywhile True:try:num1 = int(input('Enter the first number: '))num2 = int(input('Enter the second number: '))print(num1 / num2)breakexcept ValueError:print('Please input a digit!')except ZeroDivisionError:print('The second number cannot be zero!')File改写prog9-9.pybreak语句的位置31# Filename: prog9-11.pywhile True:try:num1 = int(input('Enter the first number: '))num2 = int(input('Enter the second number: '))print(num1 / num2)breakexcept Exception as err:print(err)Filebreak语句的位置并非固定放在else子句中,有时也会放在except子句中,完全根据需要而定。例如,prog9-10可以改写成如下形式:32break语句的位置33# Filename: prog9-12.pyaList = [1, 2, 3, 4, 5]i = 0while True:try:print(aList[i])except IndexError:print('index error')breakelse:i += 1File9.2.4 finally子句34finally子句可以用在try语句中,无论是否发生异常, finally子句中的语句块都要被执行。观察下面的程序及其输入和输出结果。35finally子句36# Filename: prog9-13.pydef finallyTest():try:x = int(input('Enter the first number: '))y = int(input('Enter the second number: '))print(x / y)return 1except Exception as err:print(err)return 0finally:print('It is a finally clause.')result = finallyTest()print(result)FileEnter the first number: 3Enter the second number: 50.6It is a finally clause.1Enter the first number: 3Enter the second number: 0division by zeroIt is a finally clause.03738399.3上下文管理器和with语句4041上下文管理器(Context Manager)和with语句42# Filename: prog9-14.pytry:f = open('data.txt')for line in f:print(line, end = '')except IOError:print('Cannot open the file!')finally:f.close()File43上下文管理器(Context Manager)和with语句44# Filename: prog9-15.pywith open('data.txt') as f:for line in f:print(line, end='')File上下文管理器定义和控制代码块执行前的准备动作及执行后的收尾动作通过with语句在支持上下文管理协议的对象(如文件对象)上方便地进行使用with 上下文管理表达式 as 变量:语句序列程序prog9-15首先打开当前目录下的data. txt文件并将创建的文件对象赋给变量f,执行with语句的for循环将文件中的内容按行输出,如果文件不存在,则会产生FileNot-FoundError异常。with语句在文件结束后会自动关闭文件,因此不再需要close()方法。相比 try-finally语句, with语句更精简和健壮,所以是Python中操作文件和数据库等对象时的推荐用法。45小结9.446小结474849 展开更多...... 收起↑ 资源预览