0

If the code in a "try" block fails, is it a Pythonic way to rectify the error in the "except" block?

I have come across both these kinds of code snippets:

import os
import random

workdir = str(random.randint(10**11, 10**12-1))
try:
    os.mkdir(workdir)
except FileExistsError:
    workdir = str(random.randint(10**11, 10**12-1))
    os.mkdir(workdir)
print('Created directory ' + workdir)
os.chdir(workdir)
print('Changed to directory ' + os.getcwd())
import os
import random

workdir = str(random.randint(10**11, 10**12-1))
try:
    os.mkdir(workdir)
    print("Directory " , workdir ,  " created") 
except FileExistsError:
    print("Directory " , workdir,  " already exists")

Is one preferred over the other?

Dibakar Aditya
  • 3,893
  • 1
  • 14
  • 25
  • 2
    as long as its an Except catching specific types of errors, the idea is that you have an idea of what causes it, and can still be capable of running the program in well defined behaviour. So, really, it depends on the cause of error, and yes, it is perfectly acceptable to do operations inside an except block, as long as the reason for entering the block is still clear while writing the code. – Paritosh Singh Mar 24 '19 at 18:34
  • 2
    In first code snippet there is still a chance to get `FileExistsError` in the `except` block, so the second is preferred in this concrete case. – sanyassh Mar 24 '19 at 18:41
  • As said by @ParitoshSingh this is why the try/except clause exists in the first place – MaximGi Mar 24 '19 at 18:47
  • Be aware that there is an existing Python module that creates temporary files and folders: https://docs.python.org/3/library/tempfile.html. – jarmod Mar 24 '19 at 18:51
  • 1
    A corrected version of the first one would be to use a `while` loop to create directories until a new one *is* created. That said, don't try to generate your own random directory names; use `tempfile.mkdtemp` instead. – chepner Mar 24 '19 at 18:55
  • Thanks for all the answers. The `tempfile.TemporaryDirectory()` method is exactly what I was looking for. I am just beginning to learn programming on my own and that's where it gets tricky. – Dibakar Aditya Mar 24 '19 at 19:21

1 Answers1

2

Using exceptions is actually a pythonic way.There's a principle called EAFP which stands for 'Easier to Ask for Forgiveness than Permission'. You can read more about it here

The second code snippet looks better than the first one because there's still a chance to generate the same number.

Desiigner
  • 2,136
  • 5
  • 26
  • 47