资源简介 (共49张PPT)第9章 异常Chap9 ExceptionsPython中的异常9.1Python程序设计错误语法错误运行时错误逻辑错误6 = x * 2x = 3 / 0area = 2 * 3.14 * 3PythonPython异常(Exception)Traceback (most recent call last):File "<pyshell#0>",line 1, in <module>1/0ZeroDivisionError: division by zero>>>1/ 0SourceTraceback (most recent call last):File "<pyshell#1>", line 1, in <module>y = x + 1NameError: name 'x' is not defined>>> y = x + 1Source用异常对象(exception object)表示异常情况PythonPython用异常对象(exception object)表示异常情况,遇到错误时如果异常对象没有Python异常查看异常类dir(__builtins__)类名描述BaseException所有异常的基类Exception常规异常的基类AttributeError对象不存在此属性IndexError序列中无此索引IOError输入/输出操作失败KeyboardInterrupt用户中断执行(通常输入Ctr-C)KeyError映射中不存在此键NameError找不到名字(变量)SyntaxErrorPython语法错误TypeError对类型无效的操作ValueError传入无效的参数ZeroDivisionError除(或取模)运算的第二个参数为0Python异常处理ify != 0:print(x/ y)else:print('division by zero')VStry-except异常处理语句可以用if语句判断除数的特殊情况后单独处理,形如:但这种做法不够灵活,有时效率也不高。Python中提供了简单自然的异常处理方法。因为这些实例可以被引发、捕捉,对捕捉到的异常可以进行处理,以免程序因为异常而终止运行。Python捕捉异常9.2Python异常Enter the firstnumber:aTraceback (most recent call last):File "C:\Python\programs\exception1.py", line 1, in <module>num1 =int(input('Enter the first number: '))ValueError: invalid literal forint() with base 10: 'a'# Filename: prog9-1.pynum1 =int(input('Enterthe firstnumber: '))num2 =int(input('Enterthesecondnumber: '))print(num1/ num2)FilePython9.2.1 try-except语句PythonPythontry-except语句# Filename: prog9-2.pytry:num1=int(input('Enter the first number: '))num2=int(input('Enter the second number: '))print(num1/ num2)exceptValueError:print('Please input a digit!')Filetry:被检测的语句块except Exception:异常处理语句块PythonPythontry-except语句# Filename: prog9-3.pytry:num1=int(input('Enterthefirstnumber: '))num2=int(input('Enterthesecondnumber: '))print(num1/ num2)exceptZeroDivisionError:print('Thesecondnumbercannotbezero!')FilePythonPython9.2.2多个except子句和一个except块捕捉多个异常Python多个except子句# Filename: prog9-4.pytry:num1=int(input('Enterthefirstnumber: '))num2=int(input('Enterthesecondnumber: '))print(num1/ num2)exceptValueError:print('Pleaseinput a digit!')exceptZeroDivisionError:print('Thesecondnumbercannotbezero!')FilePython一个except块捕捉多个异常# Filename: prog9-5.pytry:num1=int(input('Enterthefirstnumber: '))num2=int(input('Enterthesecondnumber: '))print(num1/ num2)except(ValueError,ZeroDivisionError):print('Invalidinput!')FilePython空except子句# Filename: prog9-6.pytry:num1=int(input('Enterthefirstnumber: '))num2=int(input('Enterthesecondnumber: '))print(num1/ num2)except:print('Somethingwentwrong!')File一了百了:except:如果想要捕捉所有的异常,可以使用空的except子句Pythonas子句# Filename: prog9-7.pytry:num1 =int(input('Enterthefirstnumber: '))num2 =int(input('Enterthesecondnumber: '))print(num1 / num2)exceptExceptionaserr:print('Somethingwentwrong!')print(err)FilePythonPythonas子句try:被检测的语句块except异常类名as错误原因名:异常处理语句块print(错误原因名)Python9.2.3 else子句Pythonelse子句# Filename: prog9-8.pytry:num1=int(input('Enter the first number: '))num2=int(input('Enterthesecondnumber: '))print(num1/ num2)except(ValueError,ZeroDivisionError):print('Invalidinput!')else:print('Aha, I amsmart.')FileEnter the first number: 3Enter the second number: 50.6Aha,I amsmart.如果输入正确没有引发异常,则跳过except执行else子句Python程序prog9-2~prog9-8 中虽然都做了异常处理,但只有简单的提示信息不能再次输人,如果想要在产生异常后能多次输入直到正确为止,则可以在外层加上while True语句和else子句。Python加入循环# Filename: prog9-9.pywhile True:try:num1 =int(input('Enter the first number: '))num2 =int(input('Enterthesecondnumber: '))print(num1 / num2)exceptValueError:print('Pleaseinputa digit!')exceptZeroDivisionError:print('Thesecondnumbercannotbezero!')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.6PythonPythonbreak语句的位置# Filename: prog9-9’.pywhile True:try:num1=int(input('Enter the first number: '))num2=int(input('Enterthesecondnumber: '))print(num1/ num2)breakexceptValueError:print('Pleaseinputa digit!')exceptZeroDivisionError:print('Thesecondnumbercannotbezero!')File改写prog9-9.pyPythonbreak语句的位置# Filename: prog9-11.pywhile True:try:num1=int(input('Enterthefirstnumber: '))num2=int(input('Enterthesecondnumber: '))print(num1/ num2)breakexceptExceptionaserr:print(err)Filebreak语句的位置并非固定放在else子句中,有时也会放在except子句中,完全根据需要而定。例如,prog9-10可以改写成如下形式:PythonPythonbreak语句的位置# Filename: prog9-12.pyaList= [1, 2, 3, 4, 5]i= 0while True:try:print(aList[i])exceptIndexError:print('indexerror')breakelse:i+= 1FilePython9.2.4 finally子句Pythonfinally子句可以用在try语句中,无论是否发生异常,finally子句中的语句块都要被执行。观察下面的程序及其输入和输出结果。Pythonfinally子句# Filename: prog9-13.pydeffinallyTest():try:x =int(input('Enter the first number: '))y =int(input('Enterthesecondnumber: '))print(x / y)return1exceptExceptionaserr:print(err)return0finally:print('Itis 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.0PythonPythonPythonPython9.3上下文管理器和with语句PythonPython上下文管理器(Context Manager)和with语句# Filename: prog9-14.pytry:f=open('data.txt')forlineinf:print(line, end ='')exceptIOError:print('Cannotopenthefile!')finally:f.close()FilePythonPython上下文管理器(Context Manager)和with语句# Filename: prog9-15.pywithopen('data.txt')asf:forlineinf:print(line, end='')File上下文管理器定义和控制代码块执行前的准备动作及执行后的收尾动作通过with语句在支持上下文管理协议的对象(如文件对象)上方便地进行使用with上下文管理表达式as变量:语句序列Python程序prog9-15首先打开当前目录下的data. txt文件并将创建的文件对象赋给变量f,执行with语句的for循环将文件中的内容按行输出,如果文件不存在,则会产生FileNot-FoundError异常。with语句在文件结束后会自动关闭文件,因此不再需要close()方法。相比 try-finally语句, with语句更精简和健壮,所以是Python中操作文件和数据库等对象时的推荐用法。Python小结9.4Python小结Python本章主要介绍了如下内容:异常。Pyuhon 中用异常对象表示异常情况。每一个异常是异常类的实例。Python中内建的异常类很多,其中BaseException 是所有异常的基类,Exception 是常规鼻常类。tr-except 语句。将被检测的和异常处理语句序列分别放入 try和 except 中,如果被,检测的语句序列中有异常,则执行异常处理语句序列;否则,忽略except后的语句。一个 try语句中可以有多个 except 子句,也可以用一个 except 块捕捉多个异常。try-except-else 语句。如果 try 中没有异常,那么except子句将被跳过,执行 eln的语句。t-fnally 语句。finaly中的语句无论是否有异常最后都要执行。raise 语句。除由Python 解释器引发的异常外,还可以利用 raise 语句由程序主动发异常,可以是系统产生的或由用户自定义的异常名。with 语句。Python 中支持上下文管理协议的对象都可以使用 with 语句,with 语句精简、健壮,是Python 中操作文件和数据库等对象时的推荐使用语句。PythonPython 展开更多...... 收起↑ 资源预览