zoukankan      html  css  js  c++  java
  • Python学习(十一)--异常

    一、定义

    Python用异常对象来表示异常情况。遇到错误后,会引发异常,如果异常对象并没有被处理或者捕捉,程序就会用所谓的回溯(traceback)终止执行。

    每个异常都是一些类的实例,这些实例可以被引发,并且可以用很多方法进行捕捉。

    二、raise语句引发异常

    >>> raise Exception
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    Exception
    >>> raise Exception('error error')
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    Exception: error error

    Exception是所有异常类的基类。其它一些常见异常类可以查看手册。上面两个例子都通过raise语句引发了异常。第二个例子里加上了错误信息。

    三、捕捉异常

    通过try/except语句可以实现捕捉异常的功能。针对具体的异常,可以在except后面加上异常类,如下:

    try:
       x = input('Enter the first number: ')
       y = input('Enter the second number: ')
       print x/y
    except ZeroDiyisionError:
       print "the second number can't be zero! "

    如果except后面什么异常类也不加,那么就会捕捉所有异常。

    如果捕捉到了异常又想重新引发它,可以调用不带参数的raise。

    try:
        x = input('Enter the first number: ')
        y = input('Enter the second number: ')
        print x/y
    except ZeroDiyisionError:
        raise 

    四、捕捉多个异常

    第一种方法可以使用多个except子句,针对每种情况说明。

    try:
        x = input('Enter the first number: ')
        y = input('Enter the second number: ')
        print x/y
    except ZeroDiyisionError:
        print "the second number can't be zero! "
    except TypeError:
        print "That was't a number!
    当然也可以将异常类型作为元组列出。
    try:
        x = input('Enter the first number: ')
        y = input('Enter the second number: ')
        print x/y
    except (TypeError, NameError):
        print "Your numbers were bogus..."

    五、访问异常对象本身

    try:
        x = input('Enter the first number: ')
        y = input('Enter the second number: ')
        print x/y
    except (TypeError, NameError),e:
        print e

    通过如上方式就可以将错误打印出来。

    六、使用else 、finally语句

    在捕捉异常的时候,也可以联合使用else、finally语句来执行一些操作。

    x = None
    try:
        x = 1/0
    except NameError:
        print "Unknown variable"
    else: #无异常时会执行else语句
        print "That went well!"
    finally: #不管是否有异常,都会执行finally语句
        print "Cleaning up"
  • 相关阅读:
    设计模式单例模式的实现方式
    Springboot,SSM框架比较,区别
    多线程系列之自己实现一个 lock 锁
    springBoot 自动配置原理自己新建一个 starter
    Hashmap 实现方式 jdk1.7 和 1.8区别
    给WPF中的DataGrid控件添加右键菜单(ContextMenu),以便用户可以显示或者隐藏DataGrid中的列,并且下次运行时依然保持上次关闭时的列的布局
    WPF XAML页面 无智能感知
    【读书笔记】排列研究排列中的代数组合学
    使用Mathematica做序列的DTFT的几个例子
    BGF bivariate generating function 双变量生成函数
  • 原文地址:https://www.cnblogs.com/mujiujiu/p/7837543.html
Copyright © 2011-2022 走看看