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

    当你的程序中出现异常情况时就须要异常处理。比方当你打开一个不存在的文件时。当你的程序中有一些无效的语句时,Python会提示你有错误存在。

    以下是一个拼写错误的样例。print写成了Print。

    Python是大写和小写敏感的。因此Python将引发一个错误:

    >>> Print 'Hello World'
        File "<stdin></stdin>", line 1
          Print 'Hello World'
                            ^
    SyntaxError: invalid syntax
    
    >>> print 'Hello World'
    Hello World
    

    1、try...except语句

    try...except语句能够用于捕捉并处理错误。

    通常的语句放在try块中,错误处理语句放在except块中。

    示比例如以下:

    #!/usr/bin/python
    # Filename: try_except.py
    
    import sys
    
    try:
    	s = raw_input('Enter something --> ')
    except EOFError:#处理EOFError类型的异常
    	print '/nWhy did you do an EOF on me?'
    	sys.exit() # 退出程序
    except:#处理其他的异常
    	print '/nSome error/exception occurred.'
    	
    print 'Done'
    
    执行输出例如以下:
    $ python try_except.py
    Enter something -->
    Why did you do an EOF on me?
    
    $ python try_except.py
    Enter something --> Python is exceptional!
    Done
    
    说明:每一个try语句都必须有至少一个except语句。假设有一个异常程序没有处理。那么Python将调用默认的处理器处理,并终止程序且给出提示。

    2、引发异常

    你能够用raise语句来引发一个异常。异常/错误对象必须有一个名字。且它们应是Error或Exception类的子类。
    以下是一个引发异常的样例:
    #!/usr/bin/python
    #文件名称: raising.py
    
    class ShortInputException(Exception):
    	'''你定义的异常类。

    ''' def __init__(self, length, atleast): Exception.__init__(self) self.length = length self.atleast = atleast try: s = raw_input('请输入 --> ') if len(s) < 3: raise ShortInputException(len(s), 3) # raise引发一个你定义的异常 except EOFError: print '/n你输入了一个结束标记EOF' except ShortInputException, x:#x这个变量被绑定到了错误的实例 print 'ShortInputException: 输入的长度是 %d, / 长度至少应是 %d' % (x.length, x.atleast) else: print '没有异常发生.'

    执行输出例如以下:
    $ python raising.py
    请输入 -->
    你输入了一个结束标记EOF
    
    $ python raising.py
    请输入 --> --> ab
    ShortInputException: 输入的长度是 2, 长度至少应是 3
    
    $ python raising.py
    请输入 --> abc
    没有异常发生.
    

    3、try...finally语句

    当你正在读文件或还未关闭文件时发生了异常该怎么办呢?你应该使用try...finally语句以释放资源。

    示比例如以下:

    #!/usr/bin/python
    # Filename: finally.py
    
    import time
    
    try:
    	f = file('poem.txt')
    	while True: # 读文件的一般方法
    		line = f.readline()
    		if len(line) == 0:
    			break
    		time.sleep(2)#每隔两秒输出一行
    		print line,
    finally:
    	f.close()
    	print 'Cleaning up...closed the file'
    
    执行输出例如以下:
    $ python finally.py
    Programming is fun
    When the work is done
    Cleaning up...closed the file
    Traceback (most recent call last):
      File "finally.py", line 12, in ?
        time.sleep(2)
    KeyboardInterrupt
    

    说明:我们在两秒这段时间内按下了Ctrl-c。这将产生一个KeyboardInterrupt异常,我们并没有处理这个异常,那么Python将调用默认的处理器,并终止程序,在程序终止之前,finally块中的语句将运行。

  • 相关阅读:
    接口默认值引发Qt调用DLL异常
    360杀毒引发的DLL调用异常
    VS2012基于QT5.1自定接口及插件并实现动态加载
    Qt调用C的DLL
    Qt动态多语言的实现(VS2012开发)
    Qt在VS2012中引用QtWidgets时报GLES2/gl2.h无法打开错误的解决办法
    php判断某字符串是否不以数字或其他特殊字符开头
    mysql的数据类型int、bigint、smallint 和 tinyint取值范围
    28个jQuery性能优化的建议
    主题:iframe高度的自适应
  • 原文地址:https://www.cnblogs.com/gccbuaa/p/6897552.html
Copyright © 2011-2022 走看看