0

I'm downloading images using urllib2 with an http proxy.

Is there a way to handle connection issues / exceptions? For example, if proxy is down or connection is refused.

This is my code:

proxy = urllib2.ProxyHandler({'http': '127.0.0.1:4040'})
opener = urllib2.build_opener(proxy)
urllib2.install_opener(opener)
download_image = urllib2.urlopen(image_url)
user3403945
  • 211
  • 1
  • 2
  • 3
  • Are you asking how to use `try:` / `except:` in Python? – tripleee Mar 11 '14 at 21:39
  • @tripleee Sort of. I'm new to python. I'm just not sure how exactly to determine a connection issue (rather than 404, or other error types). build_opener and install_opener don't seem to throw any exceptions, just urlopen. – user3403945 Mar 11 '14 at 21:51

1 Answers1

0

When specifying a try: except: you can specify the particular error that you want to check for in the except: For example

text = 'Put anything here'
try:
    val = int(text)
except ValuError:
    print 'text was not an integer'

Note that any other errors that are raised would be passed through and handled by the regular system processing.

In your case, you would use the exception to pick up the error that is being thrown by the urlopen.

Python Exceptions Handling

SYNTAX: Here is simple syntax of try....except...else blocks:

try: You do your operations here; ......................
except ExceptionI: If there is ExceptionI, then execute this block.
except ExceptionII: If there is ExceptionII, then execute this block.
else: If there is no exception then execute this block.

Here are few important points about the above-mentioned syntax:

A single try statement can have multiple except statements. This is useful when the try block contains statements that may throw different types of exceptions.

You can also provide a generic except clause, which handles any exception.

After the except clause(s), you can include an else-clause. The code in the else-block executes if the code in the try: block does not raise an exception.

The else-block is a good place for code that does not need the try: block's protection.

sabbahillel
  • 4,357
  • 1
  • 19
  • 36