Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent try catching every possible line in python?

Tags:

I got many lines in a row which may throw an exception, but no matter what, it should still continue the next line. How to do this without individually try catching every single statement that may throw an exception?

try:     this_may_cause_an_exception()     but_I_still_wanna_run_this()     and_this()     and_also_this() except Exception, e:     logging.exception('An error maybe occured in one of first occuring functions causing the others not to be executed. Locals: {locals}'.format(locals=locals())) 

Let's see above code, all functions may throw exceptions, but it should still execute the next functions no matter if it threw an exception or not. Is there a nice way of doing that?

I dont wanna do this:

try:     this_may_cause_an_exception() except:     pass try:     but_I_still_wanna_run_this() except:     pass try:     and_this() except:     pass try:     and_also_this() except:     pass 

I think code should still continue to run after an exception only if the exception is critical (The computer will burn or the whole system will get messed up, it should stop the whole program, but for many small things also exceptions are thrown such as connection failed etc.) I normally don't have any problems with exception handling, but in this case I'm using a 3rd party library which easily throws exceptions for small things.

After looking at m4spy's answer, i thought wouldn't it be possible, to have a decorator which will let every line in the function execute even if one of them raises an exception.

Something like this would be cool:

def silent_log_exceptions(func):     @wraps(func)     def _wrapper(*args, **kwargs):         try:             func(*args, **kwargs)         except Exception:             logging.exception('...')             some_special_python_keyword # which causes it to continue executing the next line     return _wrapper 

Or something like this:

def silent_log_exceptions(func):     @wraps(func)     def _wrapper(*args, **kwargs):         for line in func(*args, **kwargs):             try:                 exec line             except Exception:                 logging.exception('...')     return _wrapper    @silent_log_exceptions def save_tweets():     a = requests.get('http://twitter.com)     x = parse(a)     bla = x * x 
like image 726
Sam Stoelinga Avatar asked Jun 05 '12 14:06

Sam Stoelinga


People also ask

How do you handle all exceptions in Python?

To avoid such a scenario, there are two methods to handle Python exceptions: Try – This method catches the exceptions raised by the program. Raise – Triggers an exception manually using custom exceptions.

Does exception catch all exceptions Python?

Try and Except Statement – Catching all ExceptionsTry and except statements are used to catch and handle exceptions in Python. Statements that can raise exceptions are kept inside the try clause and the statements that handle the exception are written inside except clause.

What can be used in the except block to catch all exceptions in Python?

Catching Specific Exceptions in Python A try clause can have any number of except clauses to handle different exceptions, however, only one will be executed in case an exception occurs. We can use a tuple of values to specify multiple exceptions in an except clause.


2 Answers

for func in [this_may_cause_an_exception,              but_I_still_wanna_run_this,              and_this,              and_also_this]:     try:         func()     except:         pass 

There are two things to notice here:

  • All actions you want to perform have to represented by callables with the same signature (in the example, callables that take no arguments). If they aren't already, wrap them in small functions, lambda expressions, callable classes, etc.
  • Bare except clauses are a bad idea, but you probably already knew that.

An alternative approach, that is more flexible, is to use a higher-order function like

def logging_exceptions(f, *args, **kwargs):     try:         f(*args, **kwargs)     except Exception as e:         print("Houston, we have a problem: {0}".format(e)) 
like image 188
Fred Foo Avatar answered Oct 07 '22 06:10

Fred Foo


I ran into something similar, and asked a question on SO here. The accepted answer handles logging, and watching for only a specific exception. I ended up with a modified version:

class Suppressor:     def __init__(self, exception_type, l=None):         self._exception_type = exception_type         self.logger = logging.getLogger('Suppressor')         if l:             self.l = l         else:             self.l = {}     def __call__(self, expression):         try:             exec expression in self.l         except self._exception_type as e:             self.logger.debug('Suppressor: suppressed exception %s with content \'%s\'' % (type(self._exception_type), e)) 

Usable like so:

s = Suppressor(yourError, locals())  s(cmdString) 

So you could set up a list of commands and use map with the suppressor to run across all of them.

like image 26
Spencer Rathbun Avatar answered Oct 07 '22 05:10

Spencer Rathbun