python 使用try_在python中使用try进行return的警告

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值