0

sample:

with suppress(Exception)
    os.remove('test1.log')
    os.remove('test2.log')

try:
    os.remove('test1.log')
    os.remove('test2.log')
except:
    pass

test2.log will not be deleted if test1.log isn't exist because FileNotFoundError. So how to process odd code after an exception happened, or how to prevent an exception been throw?

3 Answers3

0

In a try-except if an exception is triggered, it will go the the except part than continue from there. So if you want to make sure both remove are attempted, do this:

try:
    os.remove('test1.log')
except:
    pass

try:
    os.remove('test2.log')
except:
    pass

Alternatively, you can try checking if the file exists, before deleting it:

if os.path.exists('test1.log'):
   os.remove('test1.log')
if os.path.exists('test2.log'):
   os.remove('test2.log')
tituszban
  • 4,797
  • 2
  • 19
  • 30
0

As the duplicate explains, you can't just suppress the exceptions.

You probably want something like this:

files = ["test1.log", "test2.log"]
for file in files:
    try:
        os.remove(file)
    except:
        pass
Mars
  • 2,505
  • 17
  • 26
0

tituszban already gave a valid solution. You could also simply put your statements into a for-loop, which is shorter syntax since you don't have to repeat your try-catch blocks (especially useful when trying to delete more than 2 items).

lst = ["test1.log","test2.log"]
for element in lst:
    try:
        os.remove(element)
    except:
        pass
VeryDogeWow
  • 142
  • 7