What is the intended use of the optional else clause of the try statement in Python?
The statements in the else
block are executed if execution falls off the bottom of the try
- if there was no exception. Honestly, I've never found a need.
However, Handling Exceptions notes:
The use of the else clause is better
than adding additional code to the try
clause because it avoids accidentally
catching an exception that wasn’t
raised by the code being protected by
the try ... except statement.
So, if you have a method that could, for example, throw an IOError
, and you want to catch exceptions it raises, but there's something else you want to do if the first operation succeeds, and you don't want to catch an IOError from that operation, you might write something like this:
try:
operation_that_can_throw_ioerror()
except IOError:
handle_the_exception_somehow()
else:
# we don't want to catch the IOError if it's raised
another_operation_that_can_throw_ioerror()
finally:
something_we_always_need_to_do()
If you just put another_operation_that_can_throw_ioerror()
after operation_that_can_throw_ioerror
, the except
would catch the second call's errors. And if you put it after the whole try
block, it'll always be run, and not until after the finally
. The else
lets you make sure
- the second operation's only run if there's no exception,
- it's run before the
finally
block, and - any
IOError
s it raises aren't caught here
Why is else clause needed for try statement in python?
The difference is what happens if you get an error in the f.read() or f.close() code. In this case:
try:
f = open('foo', 'r')
data = f.read()
f.close()
except IOError as e:
error_log.write('Unable to open foo : %s\n' % e)
An error in f.read()
or f.close()
in this case would give you the log message "Unable to open foo"
, which is clearly wrong.
In this case, this is avoided:
try:
f = open('foo', 'r')
except IOError as e:
error_log.write('Unable to open foo : %s\n' % e)
else:
data = f.read()
f.close()
And error in reading or closing would not cause a log write, but the error would rise uncatched upwards in the call stack.
What's try-else good for in Python?
Usually there's no practical difference between putting code in the
end of the try block or in the else block.What is the else clause good for?
The else-clause itself is interesting. It runs when there is no exception but before the finally-clause. That is its one use-case for which there isn't a reasonable alternative.
Without the else-clause, the only option to run additional code before finalization would be the clumsy practice of adding the code to the try-clause. That is clumsy because it risks
raising exceptions in code that wasn't intended to be protected by the try-block.
The use-case of running additional unprotected code prior to finalization doesn't arise very often. So, don't expect to see many examples in published code. It is somewhat rare.
Another use-case for the else-clause it to perform actions that must occur when no exception occurs and that do not occur when exceptions are handled. For example:
recip = float('Inf')
try:
recip = 1 / f(x)
except ZeroDivisionError:
logging.info('Infinite result')
else:
logging.info('Finite result')
Lastly, the most common use of an else-clause in a try-block is for a bit of beautification (aligning the exceptional outcomes and non-exceptional outcomes at the same level of indentation). This use is always optional and isn't strictly necessary.
Is it used in some real-world code?
Yes, there are a number of examples in the standard library.
Why use else in try/except construct in Python?
The else
block is only executed if the code in the try
doesn't raise an exception; if you put the code outside of the else
block, it'd happen regardless of exceptions. Also, it happens before the finally
, which is generally important.
This is generally useful when you have a brief setup or verification section that may error, followed by a block where you use the resources you set up in which you don't want to hide errors. You can't put the code in the try
because errors may go to except
clauses when you want them to propagate. You can't put it outside of the construct, because the resources definitely aren't available there, either because setup failed or because the finally
tore everything down. Thus, you have an else
block.
else clause in try statement... what is it good for
The else
clause is useful specifically because you then know that the code in the try
suite was successful. For instance:
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
.
when is it necessary to add an `else` clause to a try..except in Python?
Actually, in the second snippet, the last line executes always.
You probably meant
try:
some_code_that_can_cause_an_exception()
code_that_needs_to_run_when_there_are_no_exceptions()
except:
some_code_to_handle_exceptions()
I believe you can use the You use the else
version if it makes the code more readable.else
variant if you don't want to catch exceptions from code_that_needs_to_run_when_there_are_no_exceptions
.
What is the usage of else: after a try/except clause
The try...except...else statement mean something like this :
try:
# execute some code
except:
# if code raises an error, execute this code
else:
# if the "try" code did not raise an error, execute this code
try / else with return in try block
http://docs.python.org/reference/compound_stmts.html#the-try-statement
The optional else clause is executed if and when control flows off the
end of the try clause.Currently, control “flows off the end” except in the case of an
exception or the execution of a return, continue, or break statement.
Related Topics
Split a String by Spaces -- Preserving Quoted Substrings -- in Python
How to Hide Console Window in Python
Importerror: Dll Load Failed: %1 Is Not a Valid Win32 Application. But the Dll's Are There
How to Have Clusters of Stacked Bars
How to Do a Recursive Sub-Folder Search and Return Files in a List
From ... Import' VS 'Import .'
Why Does Checking a Variable Against Multiple Values with 'Or' Only Check the First Value
Splitting a List into N Parts of Approximately Equal Length
How to Pass Variables Across Functions
Rolling Window for 1D Arrays in Numpy
Pandas Dataframe to List of Lists
How to Open a File Using the Open with Statement
How to Selectively Escape Percent (%) in Python Strings