简体   繁体   中英

Should I define try-except in module where function is defined or in module where it is called in Python?

Let's say I have the following 2 modules:

a.py:

def connect():
bla bla bla..

b.py:

from a import connect
connect()

should I define try-except clause for connect() in module a or b ?

So

a.py:

def connect():
    try:
        bla bla bla..
    except:
        bla bla bla..

or

b.py:

from a import connect

    try:
        connect()
    except:
        bla bla bla..

?

Btw, what would happen I have 'nested' try-except ?

a.py:

def connect():
    try:
        bla bla bla..
    except ValueError:
        bla bla bla..

b.py:

from a import connect

    try:
        connect()
    except Exception, e:
        bla bla bla..

Both seem to function fine. My preference is to keep try/catch on as 'low' of a level as possible (Close to the original error source), in order to keep my main code relatively clear if it can be helped.

Furthermore, for your last example, b.py's method would catch any exception. This might be what you want, but isn't the best behavior, since it might catch odd things you might want to handle in a more specific manner.

It honestly depends on what you expect from the try/except block. If connect() runs some code that you expect might throw a KeyError, let's say because it's assuming a dictionary has been populated, then you might want to catch that and populate the dictionary:

try:
    my_value = my_dict['my_key']
except KeyError:
    my_dict = populate_my_dict()
    connect()

However, if you don't expect an error from connect but don't want b.py to crash when anything happens, you might want to do something like

from a import connect

try:
    connect()
except StandardError as err:
    print("{filename} ran into the following error: {err}".format(filename=__name__, err=err)

It's important to never do a bare try/except block, ie never use except: as is. Catch specific errors that you expect, because otherwise you end up having code crashing and running under the hood, making it near impossible to debug.

Btw, what would happen I have 'nested' try-except?

If connect() does not throw a ValueError, connect() will crash, after which the exception is piped over to b.py . Since b.py is expecting any Exception (this is similar to a bare except block, use StandardError or UserWarning instead), the exception will be caught and the body of b.py 's except block will trigger.

should I define try-except clause for connect() in module a or b?

It would really depend on the use-case and what I mean by that is always use the try-catch statement when you possibly think there could be an error.

I don't think it would be optimal to just use a try-catch in b.py just because it's simpler . Basically, ask yourself where is the code most likely to fail ?

I mean in your particular example it seems to suggest that something in connect function might fail. So, my recommendation is not only try to find the source of the problem, but also, only wrap what might fail .

So, lets say your connect() as a dict lookup and you're concerned about that. Well, one way to solve it would be to catch the exception. So, here is how I would arrange it,

a.py:

def connect():
    # bla bla bla...
    try:
        foo = some_dict["blah"]
    except KeyError:
        pass
    # bla bla bla...

Note that this exception handling is for example purposes. Your specific implementation is up to you.

Btw, what would happen I have 'nested' try-except?

Your specific example would be translated to:

Catch an exception in a.py if it is a ValueError , if not still catch it in b.py as a general exception.

Again, to me this seems to be a consequence of you trying to handle any exceptions that might occur. As I said above, the way you should approach that instead, only trying to handle what might fail.

This code, in its current state, will handle any exception that could possibly occur. But logically, there is most likely a lot of code that is not supposed to fail. Therefore, if a complete stranger reads your code, he might think that a lot of strange things happens in your connect method when in reality you're just handing errors you shouldn't.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM