zoukankan      html  css  js  c++  java
  • Python 学习笔记 13.异常(Exception)

    转载自:http://www.xwy2.com/article.asp?id=124

    Python 的异常处理机制和 C# 类似。

    Code
    >>>>>> try:
    raise Exception("a", "b")
    except Exception,e:
    print e
    finally:
    print "final"


    (
    'a', 'b')('a', 'b')
    final
    >>>>>>

    同样可以处理多个异常筛选。

    Code
    >>>>>> try:
    raise EOFError("aa", "bb")
    except RuntimeError, e:
    print "[RuntimeErro]: ", e
    except EOFError, e:
    print "[EOFError]: ", e
    except Exception, e:
    print "[Error]: ", e
    finally:
    print "final"


    [EOFError]: (
    'aa', 'bb')
    final
    >>>>>>

    除了异常参数,我们还可以用sys的一些方法来获取异常信息。

    Code
    >>>>>> import sys
    >>>>>> try:
    raise RuntimeError("the runtime error raised")
    except:
    print sys.exc_info()


    (
    <type 'exceptions.RuntimeError'>, RuntimeError('the runtime error raised',), <traceback object at 0x00DC5CB0>)
    >>>>>>

    缺省情况下,异常类都继承自 Exception。

    Code
    >>>>>> class MyException(Exception):
    pass

    >>>>>> try:
    raise MyException("My Exception raised!")
    except:
    print sys.exc_info()


    (
    <class '__main__.MyException'>, MyException('My Exception raised!',), <traceback object at 0x00DC58F0>)
    >>>>>>
  • 相关阅读:
    bbb SOCKET CAN
    在BBB上使用CCS5开发环境
    BBB的PRU模块
    垃圾邮件分类
    yzoj 2377 颂芬梭哈 题解
    yzoj 2372 小B的数字 题解
    yzoj P2371 爬山 题解
    hdu 1007 Quoit Design 题解
    手写堆
    yzoj P1126 塔 题解
  • 原文地址:https://www.cnblogs.com/sislcb/p/1285999.html
Copyright © 2011-2022 走看看