1

How can I ignore all exceptions for a given block of code such that an exception is not only ignored, but also doesn't prevent the next line from being executed?

For example, consider the following code

#!/usr/bin/env python3
def one():
    raise Exception
    print( 'one' )
def two():
    print( 'two' )

try:
    one()
    two()
except:
    pass

I would like the above code to print two but it actually prints nothing because the "ignored" exception still prevents the execution of two().

Is it possible to actually ignore exceptions in blocks of python code?

EDIT: The application for this is for a close() function that does some cleanup when my app is exiting. It needs to happen as fast as possible and will consist of many commands (not just two as the example I used, but it could be dozens of unrelated actions). And if one line fails, it shouldn't stop the next from trying. Please tell me there's a better option than "just use more than one try block"..

Michael Altfield
  • 2,083
  • 23
  • 39
  • If you have multiple statements belonging together (especially in a try block), then those statements are usually reliant on each other. So when one fails, you don’t want to execute the next one. Exceptions are _supposed_ to cancel the execution. – poke Aug 16 '20 at 12:40
  • 1
    "Exceptions are supposed to cancel the executions" -- Sure, And choosing to ignore an exception is *supposed* to ignore exceptions. – Michael Altfield Aug 16 '20 at 13:05
  • _Catching_ an exception isn’t ignoring an exception though. – poke Aug 16 '20 at 14:05
  • I guess most of the answers to this question are invalid then https://stackoverflow.com/questions/730764/how-to-properly-ignore-exceptions – Michael Altfield Aug 16 '20 at 15:06

2 Answers2

1

This can be achieved with the fuckit python module.

Here is the code modified from your example:

#!/usr/bin/env python3
import fuckit

def one():
    raise Exception
    print( 'one' )
def two():
    print( 'two' )

@fuckit
def helper():
    one()
    two()

helper()

And an example execution:

user@disp3221:~$ sudo python3 -m pip install fuckit
Collecting fuckit
  Downloading https://files.pythonhosted.org/packages/cc/f4/0952081f9e52866f4a520e2d92d27ddf34f278d37204104e4be869c6911d/fuckit-4.8.1.zip
Building wheels for collected packages: fuckit
  Running setup.py bdist_wheel for fuckit ... done
  Stored in directory: /root/.cache/pip/wheels/a9/24/e6/a3e32536d1b2975c23ac9f6f1bdbc591d7b968e5e0ce6b4a4f
Successfully built fuckit
Installing collected packages: fuckit
Successfully installed fuckit-4.8.1
user@disp3221:~$ 

user@disp3221:~$ ./test.py 
two
user@disp3221:~$ 
Michael Altfield
  • 2,083
  • 23
  • 39
0

If you want to call two function when raised exception, you could add it in the finally block:

def one():
    raise Exception
    print( 'one' )
def two():
    print( 'two' )

try:
    one()
except:
    pass
finally:
    two()
Kevin Mayo
  • 1,089
  • 6
  • 19