Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should I use try...except while defining a function?

I find I've been confused by the problem that when I needn't to use try..except.For last few days it was used in almost every function I defined which I think maybe a bad practice.For example:

class mongodb(object):

    def getRecords(self,tname,conditions=''):
        try:
            col = eval("self.db.%s" %tname)
            recs = col.find(condition)
            return recs
        except Exception,e:
            #here make some error log with e.message

What I thought is ,exceptions may be raised everywhere and I have to use try to get them. And my question is,is it a good practice to use it everywhere when defining functions?If not are there any principles for it?Help would be appreciated!

Regards

like image 640
Young Avatar asked Dec 08 '22 03:12

Young


1 Answers

That may not be the best thing to do. Whole point of exceptions is that you can catch them on very different level than it's raised. It's best to handle them in the place where you have enough information to make something useful with them (that is very application and context dependent).

For example code below can throw IOError("[Errno 2] No such file or directory"):

def read_data(filename):
    return open(filename).read()

In that function you don't have enough information to do something with it, but in place where you actually using this function, in case of such exception, you may decide to try different filename or display error to the user, or something else:

try:
    data = read_data('data-file.txt')
except IOError:
    data = read_data('another-data-file.txt')
    # or
    show_error_message("Data file was not found.")
    # or something else
like image 71
Łukasz Avatar answered Dec 09 '22 17:12

Łukasz