Python if else within a try and except

49.7k views Asked by At

I have the following python code that works well:

try:
    with urlopen("http://my.domain.com/get.php?id=" + id) as response:
        print("Has content" if response.read(1) else "Empty - no content")
except:
    print("URL Error has occurred")

But I am trying to change the if else statement within the try to something like this: so that I can run extra code rather than just print a message

try:
    with urlopen("http://my.domain.com/get.php?id=" + id) as response:
        if response.read(1):
            print("Has content")
        else:
            print("Empty - no content")
except:
    print("URL Error has occurred")

But the above is not working, giving an error related to indent

Any ideas what's wrong?

4

There are 4 answers

1
John La Rooy On BEST ANSWER

You can put the exception into a variable and print that too

except Exception as e:
    print("Error has occurred", e)

If you indenting looks like the original question, then that may be your problem - mixing tabs with spaces

0
AronVietti On

You're missing quotation marks in the first if. Should be

if response.read(1):
    print("Has content")
0
Pablo V. On

You can try an else clause to run your code

From http://docs.python.org/2/tutorial/errors.html

The try ... except statement has an optional else clause, which, when present, must follow all except clauses. It is useful for code that must be executed if the try clause does not raise an exception. For example:

for arg in sys.argv[1:]:
    try:
        f = open(arg, 'r')
    except IOError:
        print 'cannot open', arg
    else:
        print arg, 'has', len(f.readlines()), 'lines'
        f.close()
0
dawg On

You should separate different areas that an exception could occur with different try blocks.

Specifically, rather than surround with with a try block, use the contextlib module to handle these details. This is straight out of PEP 343, example 6:

from contextlib import contextmanager

@contextmanager
def opened_w_error(filename, mode="r"):
    try:
        f = open(filename, mode)
    except (IOError, err):
        yield None, err
    else:
        try:
            yield f, None
        finally:
            f.close()   

with opened_w_error('/tmp/file.txt', 'a') as (f, err):
    if err:
        print ("IOError:", err)
    else:
        f.write("guido::0:0::/:/bin/sh\n")