Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'...

like image 438
jerome Avatar asked Aug 31 '11 21:08

jerome


People also ask

How do you catch a specific error in Python?

Catching Specific Exceptions in PythonA try clause can have any number of except clauses to handle different exceptions, however, only one will be executed in case an exception occurs. We can use a tuple of values to specify multiple exceptions in an except clause.

How do you except all errors in Python?

Another way to catch all Python exceptions when it occurs during runtime is to use the raise keyword. It is a manual process wherein you can optionally pass values to the exception to clarify the reason why it was raised. if x <= 0: raise ValueError(“It is not a positive number!”)

How do you handle multiple exceptions with a single except clause?

You can also handle multiple exceptions using a single except clause by passing these exceptions to the clause as a tuple . except (ZeroDivisionError, ValueError, TypeError): print ( "Something has gone wrong.." ) Finally, you can also leave out the name of the exception after the except keyword.


1 Answers

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.

like image 143
Sam Dolan Avatar answered Oct 04 '22 08:10

Sam Dolan