当前位置:
文档之家› python课件:Python异常
python课件:Python异常
按自己的方式出错
•异常可以在某些东西出错时自动引发。 •自己如何引发异常,以及创建自己的异常 类型。
raise语句
•为了引发异常,可以使用一个类 (exception)的子类或者实例参数调用 raise语句。 •使用类时,程序会自动创建类的一个实例。 •raise Exception •raise Exception('hyperdrive overload')
不止一个except子句
• 如果在提示符后面输入非数字类型的值,就会产生另外一 个异常:
• nter the first number:10 • enter the second number:‘hello’ • Traceback (most recent call last): • File "C:/Users/lenovo/PycharmProjects/untitled1/hello.py",
捕捉对象
•如果想让程序继续运行,但是又因为某种 原因想记录下错误,比如打印给用户看: • try: • x=input('enter the first number:') • y=input('enter the second number:') • print x/y • except (ZeroDivisionError,TypeError), e: • print e
捕捉异常
• 为了捕捉异常,并且做出一些错误处理 • try: • x=input('enter the first number:') • y=input('enter the second number:') • print x/y •except ZeroDivisionError: • print 'the second number can not be zero!'
自定义异常类
•如何创建自己的异常类?从Exception类继 承。 •class SomeCustomException(Exception): • pass
捕捉异常
• 关于异常的最有意思的地方,就是可以处理 它们(通常叫做诱捕或者捕捉异常)。 • 这个功能可以使用try/except语句来实现。 •x=input('enter the first number:') •y=input('enter the second number:') •print x/y
不止一个except子句
• 为了捕捉这个异常,可以直接在同一个 try/except语句后面加上另一个except子句: • try: • x=input('enter the first number:') • y=input('enter the second number:') • print x/y •except ZeroDivisionError: • print 'the second number can not be zero!' •except TypeError: • print 'that was not a number,was it?'
lse
•有些情况下,没有坏事发生时执行一段代 码是很有用的,可以像对条件和循环语句 那样,加上else •try: • print 'a simple task' •except: • print 'something went wrong' •else:
重复执行
•while True: • try: • x=input('enter the first number:') • y=input('enter the second number:') • print x/y • except: • print 'Your numbers were bugs!' • else:
• 如果需要用一个块捕捉多个类型的异常,可 以将它们作为元组列出来。 • try: • x=input('enter the first number:') • y=input('enter the second number:') • print x/y • except (ZeroDivisionError,TypeError,NameError):
Python异常
什么是异常
•异常事件,可能是错误,比如试图除以0, 或者是不希望经常发生的事情。 •为了能够处理这些异常事件,可以在所有 可能发生这类事件的地方都使用条件语句, 比如,让程序检查除法的分母是否为零。
异常对象
•Python用异常对象(exception object)来表示 异常情况 •如果异常对象并未被处理或捕捉,程序就 会出现所谓的回溯,终止执行
捕捉全部异常
•很多时候,程序员无法预测发生什么,也 不能对其进行准备,可以在except子句中 忽略所有的异常类。 •try: • x=input('enter the first number:') • y=input('enter the second number:') • print x/y •except :
if语句与try/except的比较
•可以使用if语句,但是如果有多个除法, 就需要加入多个if语句,而使用try/except 的话,只需要一个错误处理器。 •使用if语句,有些可能的错误不容易表达。 •异常处理不会弄乱原来的代码,而增加一 大堆的if语句检查可能的错误情况会让代 码相当难读。
用一个块捕捉两个异常
line 3, in <module> • print x/y • TypeError: unsupported operand type(s) for /: 'int' and 'str'
不止一个except子句
• 为了捕捉这个异常,可以直接在同一个try/except 语句后面加上另一个except子句: • try: • x=input('enter the first number:') • y=input('enter the second number:') • print x/y • except ZeroDivisionError: • print 'the second number can not be zero!' • except TypeError: • print 'that was not a number,was it?'