使用try的Python中的异常处理,except和finally

Like other popular languages such as Java, C#, etc, Python also offers a clean exception handling mechanism. Exception handling is pretty useful to ensure graceful running of system and make end user aware of any error in an elegant way. What will happen if there is no exception handling in place? Let us understand it with an example.

像Java,C#等其他流行语言一样,Python也提供了一种干净的异常处理机制。 异常处理对于确保系统正常运行并使最终用户以优雅的方式意识到任何错误非常有用。 如果没有适当的异常处理将会怎样? 让我们通过一个例子来理解它。

def divide_numbers(num1, num2):
    return float(num1)/num2

divide_numbers(10, 0)

What will happen if we run the above code? It will throw an exception since we are dividing 10 by zero and that is an invalid operation.

如果运行上面的代码会发生什么? 因为我们将10除以零,这将引发异常,这是无效的操作。

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in divide_numbers
ZeroDivisionError: float division by zero

We can handle this gracefully by adding a try-except clause. Modified code will look like:

我们可以通过添加try-except子句来优雅地处理此问题。 修改后的代码如下所示:

def divide_numbers(num1, num2):
    try:
        return float(num1)/num2
    except ZeroDivisionError as e:
        print "Error", e.message

divide_numbers(10, 0)

Output of above code will be:

以上代码的输出将是:

Error float division by zero

Now it seems to be a little more informative and elegant code.

现在,它似乎是一个内容更丰富,更优雅的代码。

Using finally clause

使用finally子句

finally is used to run a piece of code irrespective of any exception in the code execution. This is commonly used to close open connections, giving operation completion information to the user, etc. Following combinations are valid in the given order:

最终用于运行一段代码,而与代码执行中的任何异常无关。 通常用于关闭打开的连接,向用户提供操作完成信息等。以下组合按给定顺序有效:

try - except
try - finally
try - except - finally

Any other order or combination is invalid.

任何其他顺序或组合均无效。

A simple example to understand this approach:

一个简单的例子来了解这种方法:

def divide_numbers(num1, num2):
    print "inside function"
    result = 0
    try:
        print "inside try block"
        result = float(num1)/num2
    except Exception:
        print "inside exception block"
    finally:
        print "inside finally block"
    print "division function ends"

divide_numbers(6, 3)
divide_numbers(10, 0)

Output of above code will be:

以上代码的输出将是:

>>> divide_numbers(6, 3)
inside function
inside try block
inside finally block
division function ends

>>> divide_numbers(10, 0)
inside function
inside try block
inside exception block
inside finally block
division function ends

翻译自: https://www.pybloggers.com/2016/08/exception-handling-in-python-using-try-except-and-finally/

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值