0

Question is - where and how to use try/except and if/else operators?

For example - I have function:

# copy php.cgi script
def cpcgi(src, dst):
        try:
                shutil.copy(src, dst)
                if os.path.isfile(dst + '/php.cgi'):
                        return True
        except:
                print 'Something going wrong!'

Function stored in separate file. Next, from script it calls like:

import createvhostFuncts as fun

print 'Copying php.cgi file...'
if fun.cpcgi(vdir + 'php-cgi/php.cgi', (vdir + 'php-cgi/' + username + '/' + domain)):
        print 'Done.\n'
else:
        exit('Error! Exit now.\n')

But - there is lot of functions in createvhostFuncts.py. Thus, I have big list of if/else calls in script and it's looks very... Odd? Useless?

So - what correct way to call functions and where better use try/except - inside function, or in script?

UPD:

For example - in BASH I can use somethig like next:

#!/usr/bin/env bash

func(){
        echo "Ya!"
}

if func; then
        echo $?
        echo "Printed"
else
        echo $?
        echo "Can't echo!"
fi

And run it with next result:

$ ./m
Ya!
0
Printed

Or with error:

#!/usr/bin/env bash

func(){
        eCCCcho "Ya!"
}

if func; then
        echo $?
        echo "Printed"
else
        echo $?
        echo "Can't echo!"
fi


$ ./m
./m: line 4: eCCCcho: command not found
127
Can't echo!
2
  • I'm not 100% sure I understand your question. Are you asking a general question about the appropriate use of try/except blocks in python, or are you asking how to nest tests? Commented Sep 3, 2014 at 18:06
  • Second one - correct way to use if/else (depending on function exit status) and try/except. As @bereal mentioned - in Python exit status doesn't used usually? (I mean - in bash I can do > echo 'TEST' && echo 'Printed' || echo 'Can't echo!' // thus - there used process exit status 0 or 1 ) Commented Sep 3, 2014 at 18:13

2 Answers 2

2

In Python they usually don't use function return value to denote the success status (like they do in C or Go), rather the function should raise an exception if something goes wrong.

def cpcgi(src, dst):
    shutil.copy(src, dst)
    if not os.path.isfile(dst + '/php.cgi')
        raise WhateverError("Failed to copy {0}".format(src))

You can intercept the exception from the calling side (within your script) or let it fall through, which in your case will cause the script termination with a stack trace. Then you don't need to wrap every single call with try..except.

(A side note) If you also don't want the stack trace to be displayed, you can use sys.excepthook, like this:

def report(type, value, traceback):
    print "Error during execution {0}".format(value)

sys.excepthook = report
Sign up to request clarification or add additional context in comments.

Comments

1

It may look odd in a large file to have many try/catch blocks. It is agreed that this is acceptable and functions should throw an error instead of returning values to denote success or failure.

If no error is thrown you continue like normal

Here Is how I would be writing your code. In both cases it reaches the end of the script:

def cpcgi(src, dst):
    shutil.copy(src, dst)
    if not os.path.isfile(dst + '/php.cgi'):
        raise FailedCopyError("Could not copy {} to {}".format(src,dst))

import createvhostFuncts as fun

print 'Copying php.cgi file...'
try:
    fun.cpcgi(vdir + 'php-cgi/php.cgi', (vdir + 'php-cgi/' + username + '/' + domain)):

    # We have not encountered any errors so continue within the same code block

    a = 10
    b = 20
    c = 30

    # We encountered no errors

except FailedCopyError as e:
    # We have encountered an errof so break out of the try block.
    # We do not re-enter the try block, continue below.
    print(e) # This will print more information about the error


# We can continue here

print('The Try/Catch took care of everything')
print('Continue as if nothing happened')
d = 40
e = 50

It's definitely work reading the official python documentation

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.