How to use try ... besides function definition?

I find that I was confused by the problem that when I do not need to use try..except . Over the past few days, it has been used in almost all the functions that I defined, which, I think, can be bad practice. For instance:

 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 

I thought exceptions could occur everywhere, and I should use try to get them. And my question is: is it good to use it everywhere when defining functions? If there are no principles for him? Help will be appreciated!

Hi

+4
source share
4 answers

This may not be the best. The whole point of exceptions is that you can catch them at a completely different level than you raised. It’s best to process them where you have enough information to do something useful with them (this is very dependent on the application and context).

For example, the code below may raise IOError ("[Errno 2] There is no such file or directory"):

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

In this function, you do not have enough information to do something with it, but in the place where you actually use this function, in case of such an exception, you can try a different file name or show an 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 
+5
source

This (catching all possible exceptions very broadly) is indeed considered bad practice. You will mask the real reason for the exception.

Only select ' explicitly named exception types (which you expect from and , you can / will handle gracefully). Let the remaining (unexpected) bubbles as they should.

You can write these ( sys.excepthook ) exceptions (globally) by overriding sys.excepthook :

 import sys import traceback # ... def my_uncaught_exception_hook(exc_type, exc_value, exc_traceback): msg_exc = "".join( \ traceback.format_exception(exc_type, exc_value, exc_traceback) ) # ... log here... sys.excepthook = my_uncaught_exception_hook # our uncaught exception hook 
+5
source

You must find a balance between several goals:

  • The application should repair as many errors as possible.

  • The application should report all fatal errors with sufficient detail to correct the cause of the problem.

  • Errors can occur everywhere, but you do not want to pollute your code with error handling code.

  • Applications should not crash

To solve # 3, you can use an exception. All unhandled exceptions will abort the current transaction. Catch them at the highest level, roll back the transaction (so that the database does not become inconsistent) and either discard them again or swallow them (so that the application does not crash). For this you should use decorators . This solves # 4 and # 1.

The solution for # 2 is experience. You will learn over time what information you need to solve problems. The tough part is still having information when an error occurs. One solution is to add debug log calls in low-level methods.

Another solution is a dictionary for each stream in which you can store some bits and which you reset when an error occurs.

+4
source

another option is to wrap most of the code in an attempt: except: (for example, in a web application, one specific GUI page), and then use sys.exc_info () to print the error, as well as the stack where it is happened

 import sys import traceback try: #some buggy code x = ?? except: print sys.exc_info()[0] #prints the exception class print sys.exc_info()[1] #prints the error message print repr(traceback.format_tb(sys.exc_info()[2])) #prints the stack 
+1
source

Source: https://habr.com/ru/post/1305753/


All Articles