Python捕获多个异常

时间:2020-02-23 14:42:29  来源:igfitidea点击:

我们可以使用try-except块来捕获异常并对其进行处理。
有时我们根据参数,处理逻辑等调用一个可能引发多种类型异常的函数。
在本教程中,我们将学习如何在python中捕获多种异常。

Python捕获多个异常

假设我们有一个定义如下的函数:

import math

def square(x):
  if int(x) is 0:
      raise ValueError('Input argument cannot be zero')
  if int(x) < 0:
      raise TypeError(&#039;Input argument must be positive integer&#039;)
  return math.pow(int(x), 2)

我们可以在不同的块中同时捕获" ValueError"和" TypeError"。

while True:

  try:
      y = square(input('Please enter a number\n'))
      print(y)
  except ValueError as ve:
      print(type(ve), '::', ve)
  except TypeError as te:
      print(type(te), '::', te)

我将try-except块放入True循环中,以便可以运行捕获多个异常的情况。

输出:

Please enter a number
10
100.0
Please enter a number
-5
<class 'TypeError'> :: Input argument must be positive integer
Please enter a number
0
<class 'ValueError'> :: Input argument cannot be zero
Please enter a number
^D
Traceback (most recent call last):
File "/Users/hyman/Documents/github/theitroad/Python-3/basic_examples/python_catch_multiple_exceptions.py", line 15, in 
  y = square(input('Please enter a number\n'))
EOFError: EOF when reading a line

Process finished with exit code 1

在单个except块中捕获多个异常

如果您注意到例外的阻止代码,则两种例外类型都相同。
如果是这样,我们可以通过在except块中传递异常类型的元组来消除代码冗余。

这是上面代码的重写,其中我们在单个except块中捕获了多个异常。

while True:

  try:
      y = square(input('Please enter a number\n'))
      print(y)
  except (ValueError, TypeError) as e:
      print(type(e), '::', e)

输出将与之前完全相同。
当except块中的代码对于捕获的多个异常相同时,可以使用这种方法。