同Java一样,Pyton异常对象来表示异常情况。遇到错误后,引发异常,如果异常对象并未对处理或捕捉,程序就会用所谓的回溯(Traceback)来终止执行;
>>> 1/0
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero
程序可以通过raise Exceptin来手动抛出异常
>>> raise Exception
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
Exception
>>> raise Exception("hello exception")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
Exception: hello exception
自定义异常类型,只需要继承Exception(或其子类)即可;
>>> raise 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: exceptions must derive from BaseException
不同于C++,只有异常类才能被抛出;
>>> class MyException(Exception):
... pass
...
>>> raise MyException
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
__main__.MyException
捕获异常
try:
….
except ExceptionType1 as e:
….
except ExceptionType2:
….
raise
except (ExceptionType3, ExceptionType4):
….
except:
…
…
else:
…
finally:
…
不带参数的raise用于重新抛出异常;exception (ExceptionType3, ExceptionType4)相比与Java的单参数方式更方便了;
不带参数的except捕捉所有类型的异常,但是得不到异常对象,可以使用except BaseException as e 解决(或者Exceptin)
>>> try:
... 1/0
... except BaseException as e:
... print(e)
...
division by zero
else的块在没有引发异常时执行;finally同java;
>>> try:
... 1/0
... except ZeroDivisionError as e:
... print(e)
...
division by zero
>>> try:
... 1/0
... finally:
... print(‘finally‘)
...
finally
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
ZeroDivisionError: division by zero
>>> def f():
... try:
... return 1/0
... finally:
... return 2
...
>>> f()
2