jerome
jerome

Reputation: 111

Try/except for specific error of type Exception

I have a certain function which does the following in certain cases:

raise Exception, 'someError'

and may raise other exceptions in other cases.

I want to treat differently the cases when the function raises Exception, 'someError' and the cases where the function raises other exceptions.

For example, I tried the following, but it didn't work as I expected.

try:
    raise Exception, 'someError'
except Exception('someError'):
    print('first case')
except:
    print ('second case')

This prints 'second case'...

Upvotes: 6

Views: 8490

Answers (3)

Charlie G
Charlie G

Reputation: 544

By forcibly printing out the attributes for a specific exception I was able to find, at least for a WindowsError, where the error number is located.

import os
try:
    os.mkdir('name')  # folder already created, will error
except WindowsError as e:
    if e.winerror == 183:
        print 'This is the "Cannot create a file when that file already exists" error'
    else:
        print "This is an error I don't know about"
        raise

I would guess the other exceptions have similar attributes

Upvotes: 2

Simon Bergot
Simon Bergot

Reputation: 10582

You have to define your own exception class:

class FooErr(Exception):
    pass

try:
    raise FooErr("bar occured")
except FooErr:
    print("don't care about foo")
except:
    print("don't care about anything.")

see http://docs.python.org/tutorial/errors.html#user-defined-exceptions for more details.

Upvotes: 3

Sam Dolan
Sam Dolan

Reputation: 32532

You can look at the message property of the exception

>>> try:
...     raise Exception, 'someError'
... except Exception as e:
...     if e.message == 'someError':
...             print 'first case'
...     else:
...             print 'second case'
... 
first case

but it's pretty hacky. It'd be better to just create two separate exceptions and catch each one individually.

Upvotes: 11

Related Questions