python 捕获多个异常_Python捕获多个异常

python 捕获多个异常

We can use a try-except 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.

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

Python捕获多个异常 (Python Catch Multiple Exceptions)

Let’s say we have a function defined as follows:

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

import math


def 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.

我们可以在不同的区块中捕获ValueErrorTypeError

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 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/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 line

Process finished with exit code 1

在单个except块中捕获多个异常 (Catch Multiple Exceptions in a single except block)

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 tuple 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块中的代码对于捕获的多个异常相同时,可以使用这种方法。

GitHub Repository. GitHub存储库中检出完整的python脚本和更多Python示例。

翻译自: https://www.journaldev.com/23417/python-catch-multiple-exceptions

python 捕获多个异常

  • 6
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值