Search code examples
pythontry-except

Is it a good coding practice to perform operations in an "except" block?


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?


Solution

  • 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.