Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

except: block running even though try: ran successfully

This code is to print the most-recently-modified directory. A directory with no sub-dirs will throw and exception, so I put it in a try-except block. The code in both sections is running!?

  try:
  newest = max( [x for x in os.listdir('.') if os.path.isdir(x)], key = os.path.getmtime)
  print(newest)
  exit()
except:
  print("No directories found!")
  exit()

I see this output (‘bin’ is the correct newest sub-directory). The print from try: and except: has executed.

bin
No directories found!

What’d I miss? Thanks for your consideration.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

exit() is raising an exception. Try:

try:
    newest = max( [x for x in os.listdir('.') if os.path.isdir(x)], key = os.path.getmtime)
    print(newest)
except Exception:
    print("No directories found!")
finally:
    exit()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading