Home >Backend Development >Python Tutorial >What is the pythontry-finally statement? What role can it play?

What is the pythontry-finally statement? What role can it play?

乌拉乌拉~
乌拉乌拉~Original
2018-08-16 17:37:002880browse

Today in this article we will learn about finally exception handling in python exception handling. First we need to understand the finally statement in python. tryfinally will It will be explained and analyzed with examples in the following article.

First of all, we need to know that the try-finally statement will execute the last code regardless of whether an exception occurs.

Just like the following:

try:
<语句>
finally:
<语句>    #退出try时总会执行
raise

Next, let’s give an example:

#!/usr/bin/python
# -*- coding: UTF-8 -*-
try:
    fh = open("testfile", "w")
    fh.write("这是一个测试文件,用于测试异常!!")
finally:
    print "Error: 没有找到文件或读取文件失败"

If the opened file does not have writable permissions, the output will be as follows:

$ python test.py 
Error: 没有找到文件或读取文件失败

The same example can also be written as follows:

#!/usr/bin/python
# -*- coding: UTF-8 -*-
try:
    fh = open("testfile", "w")
    try:
        fh.write("这是一个测试文件,用于测试异常!!")
    finally:
        print "关闭文件"    
        fh.close()
except IOError:
    print "Error: 没有找到文件或读取文件失败"

When an exception is thrown in the try block, the finally block code is executed immediately.

After all statements in the finally block are executed, the exception is triggered again and the except block code is executed.

The content of the parameter is different from the exception.

In this article, we explain what the try-finally statement is. If you don’t understand, you can give it a try. After all, hands-on practice is the best way to verify what you have learned. Finally, I hope this article can bring some help to you who are learning python.

For more related knowledge, please visit the Python tutorial column on the php Chinese website.

The above is the detailed content of What is the pythontry-finally statement? What role can it play?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn