如何使try/except块内的变量公开? [英] How to make a variable inside a try/except block public?

查看:194
本文介绍了如何使try/except块内的变量公开?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在try/except块内公开变量?

How can I make a variable inside the try/except block public?

import urllib.request

try:
    url = "http://www.google.com"
    page = urllib.request.urlopen(url)
    text = page.read().decode('utf8')
except (ValueError, RuntimeError, TypeError, NameError):
    print("Unable to process your request dude!!")

print(text)

此代码返回错误

NameError:未定义名称文本"

NameError: name 'text' is not defined

如何使可变文本在try/except块之外可用?

How can I make the variable text available outside of the try/except block?

推荐答案

try语句不会创建新的作用域,但是如果对url lib.request.urlopen的调用引发异常,则不会设置text.您可能希望在else子句中使用print(text)行,以便仅在没有异常的情况下执行该行.

try statements do not create a new scope, but text won't be set if the call to url lib.request.urlopen raises the exception. You probably want the print(text) line in an else clause, so that it is only executed when there is no exception.

try:
    url = "http://www.google.com"
    page = urllib.request.urlopen(url)
    text = page.read().decode('utf8')
except (ValueError, RuntimeError, TypeError, NameError):
    print("Unable to process your request dude!!")
else:
    print(text)

如果以后需要使用text,您真的需要考虑如果对page的分配失败并且您不能调用page.read()时,它的值应该是什么.您可以在try语句之前给它一个初始值:

If text needs to be used later, you really need to think about what its value is supposed to be if the assignment to page fails and you can't call page.read(). You can give it an initial value prior to the try statement:

text = 'something'
try:
    url = "http://www.google.com"
    page = urllib.request.urlopen(url)
    text = page.read().decode('utf8')
except (ValueError, RuntimeError, TypeError, NameError):
    print("Unable to process your request dude!!")

print(text)

或在else子句中:

try:
    url = "http://www.google.com"
    page = urllib.request.urlopen(url)
    text = page.read().decode('utf8')
except (ValueError, RuntimeError, TypeError, NameError):
    print("Unable to process your request dude!!")
else:
    text = 'something'

print(text)

这篇关于如何使try/except块内的变量公开?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆