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'...
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.
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!”)
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With