Sergey
Sergey

Reputation: 1001

how to display information about the error?

please help display an error message.

def download(path, name):
    #urllib.URLopener().retrieve(prefix + path, name)
    img = urllib.request.urlopen(prefix + path).read()
    try:
        f = open(name, "wb")
        f.write(img)
    except PermissionError:
        print('PermissionError')
    except:
        print(error)
    finally:
        f.close()  

in the case of a failed write the script writes

PermissionError

but if there is another error, I need to display full information about error. not

error

is it possible to implement?

Upvotes: 1

Views: 42

Answers (2)

poke
poke

Reputation: 387825

You could do this:

try:
    …
except PermissionError:
    print('PermissionError')
except Exception as e:
    print(e)

Note that you shouldn’t just catch all exceptions like this. Especially for file operations, you could easily choose OSError as the most generic exception that could happen when trying to open the file, while leaving other critical exceptions there.

Also, using with is preferred to manually closing a file. This also makes sure that the file is closed whether you get any exception or not:

def download (path, name):
    img = urllib.request.urlopen(prefix + path).read()
    try:
        with open(name, "wb") as f:
            f.write(img)
    except PermissionError:
        print('PermissionError')

Upvotes: 2

user707650
user707650

Reputation:

def download(path, name):
    #urllib.URLopener().retrieve(prefix + path, name)
    img = urllib.request.urlopen(prefix + path).read()
    try:
        f = open(name, "wb")
        f.write(img)
    except PermissionError:
        print('PermissionError')
    except Exception as exc:
        print(exc)
    finally:
        f.close()  

But it's not a good idea to catch any and all exceptions like this; only catch exceptions that you expect there. If really bad things happen, those exceptions should propagate to the user and the program really should stop there.

In fact, if you want more failsave file opening, use a context manager through the with statement:

with open(name, "wb") as f:
    <do stuff>
<done here>

The file f is automatically closed this way; no worries with a finally statement.

Upvotes: 2

Related Questions