python 使用try
尝试/除非在python中返回 (try/except with return in python)
User code can raise built-in exceptions.Python defines try/except to handle exceptions and proceed with the further execution of program without interruption.
用户代码可能引发内置异常.Python定义了try / except来处理异常并继续执行程序而不会中断。
Let’s quickly get to an example of a basic try/except clause
让我们快速来看一个基本的try / except子句的示例
try / except语句 (try/except statements)
Assuming the file is unavailable, executing the below code will give the output as shown below.
假设文件不可用,执行以下代码将给出如下所示的输出。
try:
f = open("testfile.txt")
...except FileNotFoundError as e:
print(f" Error while reading file {e} ")Output:
Error while reading file [Errno 2] No such file or directory: 'testfile.txt'
In practical use cases such as connecting to a db or opening a file object, we may need to perform teardown operations such db closure/file closure irrespective of the block getting executed. So finally
is one such block which can be reserved for these operations as it gets executed always. Let’s looks at an example.
在实际使用情况下,例如连接到db或打开文件对象,我们可能需要执行拆解操作,例如db闭合/文件闭合,而与执行块无关。 因此, finally
一个是这样的块,因为它总是被执行,所以可以保留给这些操作。 让我们看一个例子。
try / except / finally语句 (try/except/finally statements)
try:
f = open("testfile.txt")
except FileNotFoundError as e:
print(f" Error while reading file {e} ")
finally:
print(" Closing the file ")
f.close()
So what could possibly go wrong here? Why shoul