本文共 2501 字,大约阅读时间需要 8 分钟。
python 捕获多个异常
We can use a block to catch exceptions and process them. Sometimes we call a function that may throw multiple types of exceptions depending on the arguments, processing logic etc. In this tutorial, we will learn how to catch multiple exceptions in python.
我们可以使用块来捕获异常并对其进行处理。 有时我们根据参数,处理逻辑等调用一个可能引发多种类型异常的函数。在本教程中,我们将学习如何在python中捕获多种异常。
Let’s say we have a function defined as follows:
假设我们有一个定义如下的函数:
import mathdef square(x): if int(x) is 0: raise ValueError('Input argument cannot be zero') if int(x) < 0: raise TypeError('Input argument must be positive integer') return math.pow(int(x), 2)
We can catch both ValueError
and TypeError
in different except block.
我们可以在不同的区块中捕获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)
I have put the try-except block in while True loop so that I can run the scenario of catching multiple exceptions.
我将try-except块放入True循环中,以便可以运行捕获多个异常的情况。
Output:
输出:
Please enter a number10100.0Please enter a number-5:: Input argument must be positive integerPlease enter a number0 :: Input argument cannot be zeroPlease enter a number^DTraceback (most recent call last): File "/Users/pankaj/Documents/github/journaldev/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 lineProcess finished with exit code 1
If you notice the except block code, it’s same for both the exception types. If that is the case, we can remove the code redundancy by passing the of exception types in the except block.
如果您注意到例外代码,则这两种异常类型都相同。 如果是这种情况,我们可以通过在except块中传递异常类型的来消除代码冗余。
Here is the rewrite of above code where we are catching multiple exceptions in a single except block.
这是上面代码的重写,其中我们在单个except块中捕获了多个异常。
while True: try: y = square(input('Please enter a number\n')) print(y) except (ValueError, TypeError) as e: print(type(e), '::', e)
The output will be exactly the same as earlier. We can use this approach when the code in except block is the same for multiple exceptions being caught.
输出将与之前完全相同。 当except块中的代码对于捕获的多个异常相同时,可以使用这种方法。
翻译自:
python 捕获多个异常
转载地址:http://tamzd.baihongyu.com/