在一些应用程序,我维护的地方很多,我发现它使用一个代码try/finally或try/except块一个for loop或if句子避免使用开始/结束
考虑下一个代码(不是生产代码,只是一个样本)
{$APPTYPE CONSOLE}
{$R *.res}
uses
Classes,
SysUtils;
Procedure TestNoBeginEnd;
var
i : Integer;
L1 : TStringList;
begin
for i := 1 to 10 do
try
L1:=TStringList.Create;
try
L1.Add('Bar');
L1.Add(IntToStr(i));
L1.Add('Foo');
finally
Writeln(L1.Text);
L1.Free;
end;
except
on E: Exception do
Writeln('Opps '+E.ClassName, ': ', E.Message);
end;
end;
begin
try
TestNoBeginEnd;
except
on E: Exception do
Writeln(E.ClassName, ': ', E.Message);
end;
Readln;
end.
Run Code Online (Sandbox Code Playgroud)
问题,被认为是一种不好的做法,代码嗅觉或使用try/finally或try/except而不是delphi中的begin/end存在任何缺点?
UPDATE
对于愚蠢的示例代码我很抱歉,只是为了澄清try/finally并尝试/除了不假装替换开始/结束,只是为了避免使用它(开始/结束)当存在使用时的情况try/finally或try/except不需要开始/结束.
有没有办法简化这个尝试/除了与lambda一行?
alist = ['foo','bar','duh']
for j,i in enumerate(alist):
try:
iplus1 = i+alist[j+1]
except IndexError:
iplus1 = ""
Run Code Online (Sandbox Code Playgroud)
还有其他方式:
j = '' if IndexError else trg[pos]
Run Code Online (Sandbox Code Playgroud) 我试图搜索,但我找不到任何东西。但是我可能只是没有说对。在我正在阅读的书中。Dave Kuhlman 编写的 Python 书籍 他编写了一个 try:except 语句来捕获 IOError。
def test():
infilename = 'nothing.txt'
try:
infile = open(infilename, 'r')
for line in infile:
print line
except IOError, exp:
print 'cannot open file "%s"' % infilename
Run Code Online (Sandbox Code Playgroud)
我的问题是 IOError 之后的 exp 是什么。它有什么作用,为什么会在那里?
我创建了一个函数,但可能会弹出错误.这就是为什么我想使用异常将所有错误概括为同一个消息.
但是,此函数包含多个sys.exit()调用.
因此,except如果引发错误,我希望我的代码跳转到处理程序中,除非它是由引起的sys.exit().我该怎么做呢?
try:
myFunction()
except:
print "Error running myFunction()"
def myFunction():
sys.exit("Yolo")
Run Code Online (Sandbox Code Playgroud) 当我在上下文管理器中引发任何异常时,不会运行清理代码.例如:
from contextlib import contextmanager
try:
raise BaseException()
except BaseException:
print "bye from except"
@contextmanager
def say_goodbye():
yield
print "bye from context manager"
with say_goodbye():
raise BaseException()
Run Code Online (Sandbox Code Playgroud)
将输出:
bye from except
Traceback (most recent call last):
File "", line 15, in
BaseException
Run Code Online (Sandbox Code Playgroud)
请注意,try/except正确捕获异常,而with语句则没有.有什么我不明白如何使用语句?
你可以在这里看到代码:http://pythonfiddle.com/context-manager-failing
仅供我在OSX小牛队运行python 2.7.虽然我已经能够在许多环境中重现,但我怀疑这与它有很大关系.
python exception-handling contextmanager python-2.7 try-except
我写了一个函数,应该多次尝试一个函数,直到这个工作.
def Retry(attempts,back_off,value):
for i in range(attempts):
counter = 0
while attempts > counter:
try:
x = function(value)
except:
counter =+ 1
delay = (counter * back_off) + 1
print ('trying again in {} seconds'.format(delay))
sleep(delay)
continue
break
return x
result = Retry(20,2,value)
Run Code Online (Sandbox Code Playgroud)
每次失败的尝试之后都应该是指数增长的时间间隔,即2秒后的第二次尝试,4秒后的第三次尝试,8秒后的第四次尝试,依此类推.问题在于,在我写的函数中,如果第一次尝试失败,我只会得到一系列无限的行:
trying again in 3 seconds
trying again in 3 seconds
trying again in 3 seconds
trying again in 3 seconds
trying again in 3 seconds
trying again in 3 seconds
....
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?为什么循环堆栈在那里?
我想读一个大的csv文件,所以我使用chunksizepandas 的方法迭代器.但我得到了一个ParserError所以我想使用try除了当我得到这个错误时我想传递到下一个块迭代.所以我测试了:
df = pd.read_csv("file.csv",iterator=True)
d=True
while d==True :
try:
df.get_chunk(500000)
exept ParserError :
pass
except StopIteration:
d=False
Run Code Online (Sandbox Code Playgroud)
但是我得到了这个错误:
NameError : name "ParserError" is not defined .
谢谢您的帮助 !!
request为响应编写Python2和Python3以及依赖项代码很困难,因为它们的urlopen()函数和requests.get()函数返回不同的类型:
urllib.request.urlopen()返回一个http.client.HTTPResponseurllib.urlopen(url)返回一个instancerequest.get(url)返回arequests.models.Response为了支持Python2和Python3以及不想安装request依赖项的用户,我尝试了try-except导入和get_content()函数中的"金字塔末日" :
try: # Try importing requests first.
import requests
except ImportError:
try: # Try importing Python3 urllib
import urllib.request
except AttributeError: # Now importing Python2 urllib
import urllib
def get_content(url):
try: # Using requests.
return requests.get(url).content # Returns requests.models.Response.
except NameError:
try: # Using Python3 urllib.
with urllib.request.urlopen(index_url) as response:
return response.read() # Returns http.client.HTTPResponse. …Run Code Online (Sandbox Code Playgroud) 开始学习Python,写了一个很简单的代码来练习try/except。
这是代码:
a = float(input('num1: '))
b = float(input('num2: '))
try:
result = a / b
except ValueError as e:
print ('error type: ', type (e))
print(result)
Run Code Online (Sandbox Code Playgroud)
每当我输入一个字母作为数字时,除了打印工作,但代码崩溃。
ZeroDivisionError&TypeError正在工作,但ValueError不是。
我什至将输入放在单独的 try/except 中,但它仍然无法正常工作。
我如何在此处以及在实际应用中处理此错误?
我想遍历一个可迭代列表,但要求某些元素可以是 type None。
这可能看起来像这样:
none_list = [None, [0, 1]]
for x, y in none_list:
print("I'm not gonna print anything!")
Run Code Online (Sandbox Code Playgroud)
但是,这会提示TypeError: 'NoneType' object is not iterable.
目前,我发现了错误并在NoneType之后处理。对于我的用例,这会导致大量重复的代码,因为我基本上替换了这些None值并在 for 循环中执行与最初计划相同的操作。
try:
for x, y in none_list:
print("I'm not gonna print anything!")
except TypeError:
print("But I will!")
# Deal with NoneType here
Run Code Online (Sandbox Code Playgroud)
问题:
忽略初始循环中的值TypeError并检查None值的最佳方法是什么?
try-except ×10
python ×9
python-2.7 ×2
chunks ×1
delphi ×1
iterable ×1
lambda ×1
nonetype ×1
pandas ×1
request ×1
sys ×1
try-finally ×1
typeerror ×1
urllib ×1
valueerror ×1
while-loop ×1