1

I've tried couple ways and none solved my problem. Here is my code:

for i in links.readlines():
try:
    link = urlopen(i)
except (HTTPError, URLError) as e:
    print(e.code)
else:
    <Code Goes Here>

The error massage:

AttributeError: 'URLError' object has no attribute 'code'

I need to make two Error Handling on one exception, but the problem I can't call the HTTPError attribute, I can't call the first Exception Handling at least.

rafidkarim
  • 35
  • 1
  • 6

2 Answers2

1

You can handle multiple exceptions with different except lines.

for i in links.readlines():
try:
    link = urlopen(i)
except HTTPError as e:
    print(e.code)
except URLError as e:
    <do other handling here>
else:
    <Code Goes Here>

See this link for more details on exception handling.

Community
  • 1
  • 1
bennerv
  • 86
  • 3
  • Thanks for replied. I need all the exception on the same. So if the HTTPError code 405 and URLError SSL Verify Failed, The code will be lesser. If I make it two exception I need to add SSL Verify on the URLError. – rafidkarim Mar 12 '17 at 06:32
0

HTTPError is a subclass of URLError. The instance variable code is available in HTTPError and not in the base class URLError. Hence when you are trying to handle two errors in the same except block and when URLError occurs , the instance variable code is not found.

URLError has instance variable called reason, if you want to get the reason for the error.

In fact variable reason should be available for both the error types. So instead of printing e.code print e.reason and you can achieve this using your own version of code.

for i in links.readlines():
    try:
        link = urlopen(i)
    except (HTTPError, URLError) as e:
        print(e.reason)
    else:
       <Code Goes Here>
Afaq
  • 1,146
  • 1
  • 13
  • 25