码迷,mamicode.com
首页 > 编程语言 > 详细

python基础-异常

时间:2014-06-25 16:25:40      阅读:604      评论:0      收藏:0      [点我收藏+]

标签:style   class   blog   code   ext   color   

什么是异常?

python用异常对象(exception object)来表示异常情况。遇到错误后,就会引发异常。如果异常未被处理或捕获,程序就会用所谓的回溯(traceback)终止执行。

>>> 1 / 0
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: integer division or modulo by zero

如何引发异常?

使用raise语句引发异常:可以使用一个类(Exception的子类)或者实例参数调用raise语句。使用类时,程序会自动创建实例。

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

exceptions模块中内置的异常类:

>>> import exceptions
>>> dir(exceptions)
[ArithmeticError, AssertionError, AttributeError, BaseException, BufferError, BytesWarning, DeprecationWarn
ing, EOFError, EnvironmentError, Exception, FloatingPointError, FutureWarning, GeneratorExit, IOError, I
mportError, ImportWarning, IndentationError, IndexError, KeyError, KeyboardInterrupt, LookupError, MemoryE
rror, NameError, NotImplementedError, OSError, OverflowError, PendingDeprecationWarning, ReferenceError, R
untimeError, RuntimeWarning, StandardError, StopIteration, SyntaxError, SyntaxWarning, SystemError, System
Exit, TabError, TypeError, UnboundLocalError, UnicodeDecodeError, UnicodeEncodeError, UnicodeError, Unicod
eTranslateError, UnicodeWarning, UserWarning, ValueError, Warning, WindowsError, ZeroDivisionError, __doc_
_, __name__, __package__]

自定义异常类

创建的异常类需从Exception类直接或者间接继承。

class SomeCustomException(Exception): pass

捕捉异常

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

try:
    1 / 0
except ZeroDivisionError:
    print "The second number can‘t be zero!"

捕捉异常之后重新引发异常

使用无参数的raise语句重新引发异常

class MuffledCalculator:
    muffled = False
    def calc(self, expr):
        try:
            return eval(expr)
        except ZeroDivisionError:
            if self.muffled:
                print "Division by zero is illegal"
            else:
                raise
>>> calculator = MuffledCalculator()
>>> calculator.calc(10 / 2)
5
>>> calculator.calc(10 / 0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 5, in calc
  File "<string>", line 1, in <module>
ZeroDivisionError: integer division or modulo by zero
>>> calculator.muffled = True
>>> calculator.calc(10 / 0)
Division by zero is illegal
>>>

捕捉多个异常

1.可以增加多个except子句

    try:
        1 / 0
    except ZeroDivisionError:
        print "Division by zero is illegal"
    except TypeError:
        print "That wasn‘t a number. was it?"

2.用一个块捕捉异常

    try:
        1 / 0
    except (ZeroDivisionError, TypeError, NameError):
        print "Your numbers were bogus"

捕捉对象

如果希望在except子句中访问异常对象本身,可以使用两个参数

  try:
        1 / 0
    except (ZeroDivisionError, TypeError, NameError), e:
        print e

 捕捉全部异常

  try:
        1 / 0
    except:
        print Something wrong happened

else子句

else在当未发生异常时执行

    try:
        1 / 2
    except:
        print Something wrong happened
    else:
        print normal

finally子句

不管异常是否会发生,finally子句总是会执行。它可以用来在可能的异常后面进行清理的工作。

  try:
        1/ 0
    except NameError:
        print Unknown variable
    else:
        print That went well!
    finally:
        print Cleaning up

finally用来关闭文件或者网络套接字是会非常有用。

异常和函数

如果异常在函数内引发而不被处理,它就会传播至函数调用的地方。如果在那里也没被处理,它就会继续传播,一直到达主程序。如果那里没有异常处理程序,程序就会带着堆栈跟踪中止。

例子:

>>> def faulty():
...     raise Exception(someting is wrong)
...
>>> def ignore_exception():
...     faulty()
...
>>> def handle_exception():
...     try:
...         faulty()
...     except:
...         print Exception handled
...
>>> ignore_exception()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in ignore_exception
  File "<stdin>", line 2, in faulty
Exception: someting is wrong
>>> handle_exception()
Exception handled
>>>

faulty中产生的异常通过faulty和ignore_exception传播,最终导致了堆栈跟踪。同样地,它也传播到了handle_exception,但在这个函数中被try/except语句处理。

只要异常try/except语句查看对象是否存在特定的特性:

class TestClass:
    pass

if __name__ == __main__:
    obj = TestClass()
    try:
        obj.write
    except AttributeError:
        print The object is not writeable
    else:
        print The object is writeable

 

python基础-异常,布布扣,bubuko.com

python基础-异常

标签:style   class   blog   code   ext   color   

原文地址:http://www.cnblogs.com/zjwzcnjsy/p/3806184.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!