Try Except Specific Error Messages

classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|

Try Except Specific Error Messages

brandon wallace

Hi,
?
I am try to get more specific error messages using try/except.
I ran this code with the cable unplugged to see the error message. I got

#!/usr/bin/env python3

import urllib.request

webpage = urllib.request.urlopen("http://fakewebsite.com/")
text = webpage.read().decode("utf8")


I got two errors. This:
[....]
socket.gaierror: [Errno -2] Name or service not known

and this:
[....]
urllib.error.URLError: <urlopen error [Errno -2] Name or service not known>

I tried this but got more error messages.
try:
    webpage = urllib.request.urlopen("http://fakewebsite.com/")
    text = webpage.read().decode("utf8")
except URLError as err:
    print("URLError: " + str(err))

How do I wrap urllib.request with try/except?


Reply | Threaded
Open this post in threaded view
|

Try Except Specific Error Messages

Gary Herron-2
On 04/30/2015 04:27 PM, brandon wallace wrote:

> Hi,
>  
> I am try to get more specific error messages using try/except.
> I ran this code with the cable unplugged to see the error message. I got
>
> #!/usr/bin/env python3
>
> import urllib.request
>
> webpage = urllib.request.urlopen("http://fakewebsite.com/")
> text = webpage.read().decode("utf8")
>
>
> I got two errors. This:
> [....]
> socket.gaierror: [Errno -2] Name or service not known
>
> and this:
> [....]
> urllib.error.URLError: <urlopen error [Errno -2] Name or service not known>

Note the error message here.  The exception is named
"urllib.error.URLError" NOT "URLError" as you use in the next bit of code.

You could import that specific error if you wanted to access it that way:
      from urllib.error import URLError
otherwise you should use the fully qualified name urllib.error.URLError.

>
> I tried this but got more error messages.
As a side note, that is never a useful thing to say in this group. Take
the time to tell is the actual errors message you got.  That way I don't
have to waste my time running your code to see what error message you
are getting.


> try:
>      webpage = urllib.request.urlopen("http://fakewebsite.com/")
>      text = webpage.read().decode("utf8")
> except URLError as err:
>      print("URLError: " + str(err))
>
> How do I wrap urllib.request with try/except?


--
Dr. Gary Herron
Department of Computer Science
DigiPen Institute of Technology
(425) 895-4418