zoukankan      html  css  js  c++  java
  • Python学习笔记之异常

    Python用异常对象来表示异常情况,如果异常对象未被处理或捕捉,程序就会回溯(traceback)中止执行。

    异常可以在出错时自动引发,也可以主动引发。

    异常被引发后如果不被处理就会传播至程序调用的地方,直到主程序(全局作用域),如果主程序仍然没有异常处理,程序会带着栈跟踪终止。

    raise:引发异常

    >>> raise Exception
    Traceback (most recent call last):
      File "<pyshell#1>", line 1, in <module>
        raise Exception
    Exception

      >>> raise Exception("error!!!")
      Traceback (most recent call last):
      File "<pyshell#2>", line 1, in <module>
      raise Exception("error!!!")
      Exception: error!!!

    常见内建异常类:

    类名 描述
    Exception 所有异常的基类
    AttributeError 特性引用或赋值失败时引发
    IOError 试图打开不存在文件(包括其他情况)时引发
    IndexError 在使用序列中不存在的索引时引发
    KeyError 使用映射中不存在的键引发
    NameError 找不到名字(变量)时引发
    SyntaxError 在代码为错误形式时引发
    TypeError 在内建操作或者函数应用于错误类型的对象引发 
    ValueError 在内建操作或者函数应用于正确的对象,但是该对象使用不合适的值引发
    ZeroDivision 在除法或者模除操作的第二个参数为0时引发

    自定义异常类:继承自Exception

    class DefException(Exception):pass

    捕捉异常:使用try/except语句实现>>> try:

        x =  int(input("The first num:"))
        y = int(input("The second num:"))
        print(x/y)
    except ZeroDivisionError:
        print("Error")
    
        
    The first num:5
    The second num:0
    Error
    >>> try:
        x =  int(input("The first num:"))
        y = int(input("The second num:"))
        print(x/y)
    except ZeroDivisionError:
        print("Error")
    except ValueError:
        print("TypeError")
    
        
    The first num:5
    The second num:o
    TypeError

    用一个块捕捉多个异常:

    >>> try:
        x =  int(input("The first num:"))
        y = int(input("The second num:"))
        print(x/y)
    except (ZeroDivisionError,ValueError):
        print("Error")
    
        
    The first num:5
    The second num:0
    Error

    捕捉对象:

    >>> try:
        x =  int(input("The first num:"))
        y = int(input("The second num:"))
        print(x/y)
    except (ZeroDivisionError,ValueError) as e:
        print(e)
    
        
    The first num:5
    The second num:0
    division by zero

    捕捉所有异常:

    try:
        x = int(input("The first num:"))
        y = int(input("The second num:"))
        print(x/y)
    except:
        print("some errors")
    The first num:5
    The second num:
    some errors

    这种方式会捕捉用户中止执行的企图,会隐藏所有程序员未想到并且未做好准备的错误。

    对于异常情况进行处理:

    #在输入不合法时循环,直到合法值出现退出循环
    while True:
        try:
            x = int(input("The first num:"))
            y = int(input("The second num:"))
            print(x/y)
        except:
            print("Error")
        else:
            break
    
    #运行结果
    
    The first num:5
    The second num:0
    Error
    The first num:6
    The second num:3
    2.0

     finally子句:用在可能的异常后进行清理,不管是否有异常都要执行。在同一个try语句中,不可以和except使用。

    x = None
    try:
        x = 1/0
    finally:
        print("cleaning")
        del x
    
    #结果
    cleaning
    Traceback (most recent call last):
      File "input.py", line 4, in <module>
        x = 1/0
    ZeroDivisionError: division by zero
    
    ***Repl Closed***

    可以在一条语句中组合使用try,except,else,finally

    try:
        x = 1/0else:
        print("done")
    finally:
        print("cleaning")
    
    #运行结果
    cleaning
    
    ***Repl Closed***
  • 相关阅读:
    YUM安装(卸载)KDE和GNOME
    shutdown
    linux运行级别
    [root@localhost ~]#各项解释
    常用服务端口号
    部分命令技巧
    网卡配置文件
    《移动端支付系统如何设计有效地防重失效机制?》阅读心得
    软件开发第三天(记录)
    软件开发第二天(记录)
  • 原文地址:https://www.cnblogs.com/HJhj/p/7423454.html
Copyright © 2011-2022 走看看