zoukankan      html  css  js  c++  java
  • Python的异常处理

    一.异常

        Python遇到错误后会引发异常。若异常对象未被捕捉或处理,程序会回溯(traceback)来终止运行:

    1 print 1 / 0
    2 
    3 Traceback (most recent call last):
    4   File "D:coding_filepython_fileTestPythonsrcTest	est1.py", line 1, in <module>
    5     print 1 / 0
    6 ZeroDivisionError: integer division or modulo by zero

    二.引发异常

        Python使用一个类或者实例参数调用raise语句来引发异常。

    1 raise Exception("It's an exception raised by me.")
    2 
    3 Traceback (most recent call last):
    4   File "D:coding_filepython_fileTestPythonsrcTest	est1.py", line 1, in <module>
    5     raise Exception("It's an exception raised by me.")
    6 Exception: It's an exception raised by me.

    三:捕捉多个异常
        Python使用try/except来捕捉异常。可使用一个元组列出多种类型的异常来达到一个块捕捉多个类型异常的目的。

     1 try:
     2     x = input('Please enter the first number: ')
     3     y = input('Please enter the second number: ')
     4     print x / y
     5 except (ZeroDivisionError, TypeError) as e:
     6     print e
     7  
     8 输入:
     9 Please enter the first number: 1
    10 Please enter the second number: 0
    11 
    12 运行结果:
    13 integer division or modulo by zero
    注:上面代码中的 except (ZeroDivisionError, TypeError) as e:
    e用于存放异常信息,可用于随后的打印异常信息;在Python 3.0以前可写作except (ZeroDivisionError, TypeError), e:

    四.要求用户重新输入
    可使用循环语句,使的在发生错误时,程序不断要求重新输入:
     1 while True:
     2     try:
     3         x = input('Please enter the first number: ')
     4         y = input('Please enter the second number: ')
     5         result = x / y
     6         print 'x / y equals', result
     7     except (ZeroDivisionError, TypeError) as e:
     8         print 'Invalid input:', e
     9         print 'Please enter again.'
    10     else:
    11         break
    12 
    13 输入:
    14 Please enter the first number: 1
    15 Please enter the second number: 0
    16 
    17 运行结果:
    18 Invalid input: integer division or modulo by zero
    19 Please enter again.
    20 Please enter the first number: 
    当没有发生异常时,程序正常退出(通过else:break语句)

    五.发生异常后的清理
    finally语句用于可能的异常后进行清理
     1 try:
     2     x = input('x = ?: ')
     3     y = input('y = ?: ')
     4     print x / y
     5 except (ZeroDivisionError, TypeError, NameError) as e:
     6     print e
     7 else:
     8     print 'No problem!'
     9 finally:
    10     print 'Done!'
    在上面的代码中,不论try语句是否发生异常,finally子句肯定会被执行
    
    
    
    
    
    
    
    
  • 相关阅读:
    Qt的.pro文件
    AI_八数码
    安装 MINGW GCC 4.4.0
    VC中应用Excel
    八数码问题_启发搜索
    【收集】【收藏】【转帖】game development resouce
    QT小记之在VS2005中使用QT
    [转文]VS2008 安装 Boost 1.43.0
    搬家到博客园了
    转 暴雪总裁总结游戏十条经验
  • 原文地址:https://www.cnblogs.com/jzincnblogs/p/4660269.html
Copyright © 2011-2022 走看看