1.使用一个类,应该是Excepion的子类(使用类时,程序会自动创建类的一个实例)
2.实例参数调用raise语句。
In [1]: raise Exception ---------------------------------------------------------------------------
Exception Traceback (most recent call last)
<ipython-input-1-fca2ab0ca76b> in <module>()
----> 1 raise Exception
Exception:
#raise Exception 引发一个没有任何有关错误信息的普通异常。
In [2]: raise Exception('The Hyperdrive overload') ---------------------------------------------------------------------------
Exception Traceback (most recent call last)
<ipython-input-2-3d981203beac> in <module>()
----> 1 raise Exception('The Hyperdrive overload')
Exception: The Hyperdrive overload
#添加了错误信息
#!/usr/bin/env python
# encoding: utf-8
"""
@author: kamil.liu @file: exception.py
@time: 16-5-30 上午10:56
"""
# raise Exception
# raise AttributeError
# raise IOError
# raise IndexError
# raise KeyError
# raise NameError
# raise SyntaxError
# raise TypeError
# raise ValueError
# raise ZeroDivisionError
class kamilException(Exception):
pass
print(type(kamilException))
print(dir(kamilException))
/usr/bin/python3.5 /home/kamil/PycharmProjects/untitled/test1/exception.py
<class 'type'>
['__cause__', '__class__', '__context__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setstate__', '__sizeof__', '__str__', '__subclasshook__', '__suppress_context__', '__traceback__', '__weakref__', 'args', 'with_traceback']
Process finished with exit code 0
1.所以异常都从 BaseException继承,并删除了StardardError
2.去除了异常类的序列行为和.message属性
3.用 raise Exception(args)代替 raise Exception, args语法
4.捕获异常的语法改变,引入了as关键字来标识异常实例,在Py2中:
>>> try:
... raise NotImplementedError('Error')
... except NotImplementedError, error:
... print error.message
...
Error
在Py3中:
>>> try:
raise NotImplementedError('Error')
except NotImplementedError as error: #注意这个 as
print(str(error))
Error
5.异常链,因为__context__在3.0a1版本中没有实现