ID: 19715396

中职计算机类 Python程序设计任务驱动式教程(2021人邮版) -第9章 异常 课件(共49张PPT)

日期:2026-02-11 科目: 类型:课件 查看:67次 大小:2843784B 来源:二一课件通
预览图 1/12
中职,49张,课件,异常,9章,邮版
  • cover
(课件网) 第9章 异常 Chap9 Exceptions Python中的异常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: ') ... ...

~~ 您好,已阅读到文档的结尾了 ~~