You can find documented in the section about the try statement:
If the finally clause executes a return, break or continue statement, the saved exception is discarded.
Of course, the fact that it's a documented behavior does not entirely explain the reasoning, so I offer this: a function can only exit in one of two ways, by returning a value or raising an exception. It can not do both.
Since the finally block is commonly used as a cleanup handler, it makes sense for the return to take priority here. You do have the chance to re-raise any exceptions within finally, simply by not using a return statement.
Answer from platypus on Stack OverflowHi and sorry for the noob question,
I am calling another python script as a subprocess. The python script tries to do X, and if/when it fails it MUST do Y. I had originally been handling this by doing the following:
try:
x
except:
<code to be run>For what I want to do, would it be better to simply use:
try:
x
finally:
yIf I understand correctly, I am basically using except for something finally should be used for at the moment, yes? Is there any downside to not using except for what I want to accomplish?
Run code finally before returning in except
For ... except ... finally - Ideas - Discussions on Python.org
exceptions - Using a try-finally (without catch) vs enum-state validation - Software Engineering Stack Exchange
exception - What is the intended use of the optional "else" clause of the "try" statement in Python? - Stack Overflow
Videos
It depends on whether you can deal with the exceptions that can be raised at this point or not.
If you can handle the exceptions locally you should, and it is better to handle the error as close to where it is raised as possible.
If you can't handle them locally then just having a try / finally block is perfectly reasonable - assuming there's some code you need to execute regardless of whether the method succeeded or not. For example (from Neil's comment), opening a stream and then passing that stream to an inner method to be loaded is an excellent example of when you'd need try { } finally { }, using the finally clause to ensure that the stream is closed regardless of the success or failure of the read.
However, you will still need an exception handler somewhere in your code - unless you want your application to crash completely of course. It depends on the architecture of your application exactly where that handler is.
The finally block is used for code that must always run, whether an error condition (exception) occurred or not.
The code in the finally block is run after the try block completes and, if a caught exception occurred, after the corresponding catch block completes. It is always run, even if an uncaught exception occurred in the try or catch block.
The finally block is typically used for closing files, network connections, etc. that were opened in the try block. The reason is that the file or network connection must be closed, whether the operation using that file or network connection succeeded or whether it failed.
Care should be taken in the finally block to ensure that it does not itself throw an exception. For example, be doubly sure to check all variables for null, etc.
Exceptions should be used for exceptional conditions. Throwing an exception is basically making the statement, "I can't handle this condition here; can someone higher up on the call stack catch this for me and handle it?"
Returning a value can be preferable, if it is clear that the caller will take that value and do something meaningful with it. This is especially true if throwing an exception has performance implications, i.e. it may occur in a tight loop. Throwing an exception takes much longer than returning a value (by at least two orders of magnitude).
Exceptions should never be used to implement program logic. In other words, don't throw an exception to get something done; throw an exception to state that it couldn't be done.
Some good advice I once read was, throw exceptions when you cannot progress given the state of the data you are dealing with, however if you have a method which may throw an exception, also provide where possible a method to assert whether the data is actually valid before the method is called.
For example, System.IO.File.OpenRead() will throw a FileNotFoundException if the file supplied does not exist, however it also provides a .Exists() method which returns a boolean value indicating whether the file is present which you should call before calling OpenRead() to avoid any unexpected exceptions.
To answer the "when should I deal with an exception" part of the question, I would say wherever you can actually do something about it. If your method cannot deal with an exception thrown by a method it calls, don't catch it. Let it raise higher up the call chain to something that can deal with it. In some cases, this may just be a logger listening to Application.UnhandledException.
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
finallyblock, and - any
IOErrors it raises aren't caught here
There is one big reason to use else - style and readability. It's generally a good idea to keep code that can cause exceptions near the code that deals with them. For example, compare these:
try:
from EasyDialogs import AskPassword
# 20 other lines
getpass = AskPassword
except ImportError:
getpass = default_getpass
and
try:
from EasyDialogs import AskPassword
except ImportError:
getpass = default_getpass
else:
# 20 other lines
getpass = AskPassword
The second one is good when the except can't return early, or re-throw the exception. If possible, I would have written:
try:
from EasyDialogs import AskPassword
except ImportError:
getpass = default_getpass
return False # or throw Exception('something more descriptive')
# 20 other lines
getpass = AskPassword
Note: Answer copied from recently-posted duplicate here, hence all this "AskPassword" stuff.