本文共 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/