setevoy
setevoy

Reputation: 4662

Use exception as check - is it good idea?

I have code:

    print('Adding user %s...' % user)
    # my own class with method
    sysacts.useradd()

    # check if user exist after been added
    try:
            pwd.getpwnam(user)
            print('Done.')
    except KeyError as e:
            print('ERROR! %s.\nExit.' %e)
            sys.exit(1)

But - I don't like, that user adds without checks. So - I think about remake it with next:

    print('Adding user %s...' % user)

    # check if new user exist before add it
    try:
            pwd.getpwnam(user)
            print('User already present, skipping.')

    # if no user - will return KeyError: 'getpwnam(): name not found: Username'
    except KeyError as e:
            sysacts.useradd()
            print('Done.')

So - is it normal, to use KeyError as such check? KeyError can mean and other errors too.

If no - what best way here to check user?

For example - in create directory block - I made:

    # create site files directory
    dir = virt_hosts_dir + 'vhosts/' + user + '/' + domain + '/'
    print('\nCreating new directory %s' % dir)
    # if no directory - run mkdir
    if not os.path.isdir(dir):
            try:
                    sysacts.mkdir(dir)
                    print('Done.')
            except OSError as e:
                    print('ERROR: %s' %e)
                    sys.exit(2)
    # otherwise - skip
    else:
            print('Directory %s already present, skipping.' % dir)

P.S. CentOS, Python 2.6

Upvotes: 1

Views: 183

Answers (3)

5gon12eder
5gon12eder

Reputation: 25409

The Python – unlike most of the rest of the world – people actually encourage this use of exceptions.

They call it the EAFP principle, quoting American computer scientist and United States Navy rear admiral Grace Hopper who allegedly said, it's sometimes easier to ask forgiveness than to get permission.

Exceptions are implemented efficiently in Python so there are used a lot. For example, every for loop in Python exits by internally throwing a StopIteration exception.

Upvotes: 0

kuma  DK
kuma DK

Reputation: 1861

Exceptions are not for checking.it should be used as last option if you are unable to deal with some run time issue. Most probably to catch any unexpected but foreseen issues while running. ex- db error, i/o device error. so we don't have any other option to deal with the abnormal situation except going in to a try catch.

But in your case you have to go with something like if else to handle comparisons and do selections.

Keep in mind, You have to maintain the code quality and performance in your coding.

Upvotes: 1

Karl M.W.
Karl M.W.

Reputation: 747

The general rule I operate by is:

Do you expect it to pass?

  • If I expect an action will be successful most of the time, I use exceptions.
  • If I expect an action to fail most of the time, I'll intercept it with an if statement

If there are things going on that could potentially break other actions because of a failure (or cause a system compromise), I always do the validation, verification, and sanity checking first.

But a simple one sentence answer: Using exceptions is very Pythonic, and is not at all frowned upon. It may actually help the code read better, and as you mention there could be other exception types, trap them separately:

try:
    …
except KeyError:
    …
except TypeError:
    …
except Exception:
    …

Upvotes: 2

Related Questions