Python中的异常

如何引发异常

使用raise语句

>>> raise
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: exceptions must be old-style classes or derived from BaseException, not NoneType
>>> 
>>> raise Exception("Unknown Error")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
Exception: Unknown Error

如何显示所有的内建异常

>>> import exceptions
>>> dir(exceptions) 

自定义异常

继承Exception这个异常的基类即可

>>> class CustomerException(Exception): pass    

如何捕捉异常

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

如何捕捉到异常并重新引发它

调用不带参数的raise

>>> try:
...   1/0
... except Exception:
...   print("got exception")
...   raise
... 
got exception
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
ZeroDivisionError: division by zero 

多个except子句

try:
  x = input("x:")
  y = input("y:")
  int(x)/int(y)
except ZeroDivisionError:
  print("division by zero {}/{}".format(x, y))
except ValueError:
  print("value error {}/{}".format(x, y))       

用一个块捕捉两个异常

try:
  x = input("x:")
  y = input("y:")
  int(x)/int(y)
except (ZeroDivisionError, ValueError) as e:
  print(e)
  print("error: {}/{}".format(x, y))

else

try:
  print("Hello World!")
except:
  print("Got Error!")
else:
  print("Everything is OK!")      

# Hello World!
# Everything is OK!

finally

Example 1:

try: 
  1/0
finally:
  print("Cleaning Up")  

'''   
Cleaning Up
Traceback (most recent call last):
  File "test4.py", line 2, in <module>
    1/0
ZeroDivisionError: division by zero
'''

Example 2:

try: 
  1/0
except:
  print("Unknow")
else:
  print("Well")
finally:
  print("Cleaning Up")

# Unknow
# Cleaning Up     

Python

这篇文章: 有用 无用
创建 2018-10-22 20:00:52 / 更新 2018-10-22 20:00:52