Zoomtek
Zoomtek

Reputation: 9

How to check for several exceptions within one exception block?

I want to catch several exceptions on the same line, but have different outcome depending on which exception is triggered. I'm trying to summarize a set of numbers in a text file and want to check on value and io errors.

try:
   filex = open('test.txt', 'r')
   number = filex.readline().rstrip('\n')
   added = 0
   while number != '':
    added += int(number)
    number = filex.readline().rstrip('\n')
   print(added)
   filex.close()

except (IOError,ValueError):
    if IOError:
       print('IOError')
    else:
       print('ValueError')

The issue I'm having is that it will always trigger on the first condition of the IF test.

Upvotes: 0

Views: 67

Answers (3)

Coding Cow
Coding Cow

Reputation: 81

if IOError:

I think this line checks the trueness of the class IOError. It ignores the type of error that was raised.

You could maybe do something like :

except (IOError, ValueError) as e:
    if instanceof(e, IOError):
        #...

Upvotes: 0

Aaron Bentley
Aaron Bentley

Reputation: 1380

I recommend using one clause per exception. Here is the "I'm stubborn" version:

try:
   filex = open('test.txt', 'r')
   number = filex.readline().rstrip('\n')
   added = 0
   while number != '':
    added += int(number)
    number = filex.readline().rstrip('\n')
   print(added)
   filex.close()

except (IOError,ValueError) as e:
    if isinstance(e, IOError):
       print('IOError')
    else:
       print('ValueError')

Here's the clause-per-exception version:

try:
   filex = open('test.txt', 'r')
   number = filex.readline().rstrip('\n')
   added = 0
   while number != '':
    added += int(number)
    number = filex.readline().rstrip('\n')
   print(added)
   filex.close()

except IOError:
    print('IOError')
except ValueError:
    print('ValueError')

You can see that in the first version, you have to implement type checking, which Python's exception handling would otherwise give you for free. And the second version is slightly shorter, too.

Upvotes: 0

user11544535
user11544535

Reputation:

can use two except for this condition like this

try 
  .......
except IOError:
    print('IOError')
except ValueError:
    print('ValueError')

Upvotes: 2

Related Questions