博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
使用try的Python中的异常处理,except和finally
阅读量:2520 次
发布时间:2019-05-11

本文共 2449 字,大约阅读时间需要 8 分钟。

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)/num2divide_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 "
", line 1, in
File "
", line 2, in divide_numbersZeroDivisionError: 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.messagedivide_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 - excepttry - finallytry - 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 functioninside try blockinside finally blockdivision function ends>>> divide_numbers(10, 0)inside functioninside try blockinside exception blockinside finally blockdivision function ends

翻译自:

转载地址:http://ogqwd.baihongyu.com/

你可能感兴趣的文章
Linux IPC实践(3) --具名FIFO
查看>>
Qt之模拟时钟
查看>>
第一次接触安卓--记于2015.8.21
查看>>
(转)在分层架构下寻找java web漏洞
查看>>
mac下多线程实现处理
查看>>
C++ ifstream ofstream
查看>>
跟初学者学习IbatisNet第四篇
查看>>
seL4环境配置
查看>>
Git报错:insufficient permission for adding an object to repository database .git/objects
查看>>
ajax跨域,携带cookie
查看>>
BZOJ 1600: [Usaco2008 Oct]建造栅栏( dp )
查看>>
nginx 高并发配置参数(转载)
查看>>
洛谷 CF937A Olympiad
查看>>
Codeforces Round #445 C. Petya and Catacombs【思维/题意】
查看>>
用MATLAB同时作多幅图
查看>>
python中map的排序以及取出map中取最大最小值
查看>>
ROR 第一章 从零到部署--第一个程序
查看>>
<form>标签
查看>>
vue去掉地址栏# 方法
查看>>
Lambda03 方法引用、类型判断、变量引用
查看>>