Possible Duplicate:
Python try-else可能重复:Python try-else
Comming from a Java background, I don't quite get what the else
clause is good for.
来自Java背景,我不太了解else子句的好处。
According to the docs
根据文件
It is useful for code that must be executed if the try clause does not raise an exception.
如果try子句不引发异常,则对于必须执行的代码很有用。
But why not put the code after the try block? It seems im missing something important here...
但为什么不把代码放在try块之后呢?看来我错过了一些重要的东西......
3 个解决方案
#1
10
The else
clause is useful specifically because you then know that the code in the try
suite was successful. For instance:
else子句特别有用,因为您知道try套件中的代码是成功的。例如:
for arg in sys.argv[1:]:
try:
f = open(arg, 'r')
except IOError:
print 'cannot open', arg
else:
print arg, 'has', len(f.readlines()), 'lines'
f.close()
You can perform operations on f
safely, because you know that its assignment succeeded. If the code was simply after the try ... except, you may not have an f
.
您可以安全地对f执行操作,因为您知道它的分配成功。如果代码只是在尝试之后...除外,你可能没有f。
#2
3
Consider
考虑
try:
a = 1/0
except ZeroDivisionError:
print "Division by zero not allowed."
else:
print "In this universe, division by zero is allowed."
What would happen if you put the second print
outside of the try/except/else
block?
如果将第二个打印放在try / except / else块之外会发生什么?
#3
2
It is for code you want to execute only when no exception was raised.
只有在没有引发异常时才能执行代码。
#1
10
The else
clause is useful specifically because you then know that the code in the try
suite was successful. For instance:
else子句特别有用,因为您知道try套件中的代码是成功的。例如:
for arg in sys.argv[1:]:
try:
f = open(arg, 'r')
except IOError:
print 'cannot open', arg
else:
print arg, 'has', len(f.readlines()), 'lines'
f.close()
You can perform operations on f
safely, because you know that its assignment succeeded. If the code was simply after the try ... except, you may not have an f
.
您可以安全地对f执行操作,因为您知道它的分配成功。如果代码只是在尝试之后...除外,你可能没有f。
#2
3
Consider
考虑
try:
a = 1/0
except ZeroDivisionError:
print "Division by zero not allowed."
else:
print "In this universe, division by zero is allowed."
What would happen if you put the second print
outside of the try/except/else
block?
如果将第二个打印放在try / except / else块之外会发生什么?
#3
2
It is for code you want to execute only when no exception was raised.
只有在没有引发异常时才能执行代码。