eg:
try:
myfruits = FruitFunction() #Raises some exception (unknown)
assert "orange" in myfruits #Raises AssertionError (known)
except:
# I don't know how to distinguish these two errors :(
I need to filter out one particular kind of exception (which is known) from all others that are unknown. I also need assertion to continue the same exception handling,
try:
myfruits = FruitFunction() #Raises some exception (unknown)
assert "orange" in myfruits #Raises AssertionError (known)
except AssertionError:
# Handle Assertion Errors here
# But I want the except below to happen too!
except:
# Handle everything here
I will add one real example to convey the idea more concisely:
try:
# This causes all sorts of errors
myurl = urllib.urlopen(parametes)
# But if everything went well
assert myurl.status == 202
# proceed normal stuff
except:
# print "An error occured" if any error occured
# but if it was an assertion error,
# add "it was something serious too!"
try:
try:
myfruits = FruitFunction() #Raises some exception (unknown)
assert "orange" in myfruits #Raises AssertionError (known)
except AssertionError:
# handle assertion
raise
except Exception:
# handle everything
I'm assuming you can't separate the two statements that throw the different exceptions (because they're off together in another function, for example). If you can then the following is more precise and straightforward:
try:
myfruits = FruitFunction() #Raises some exception (unknown)
try:
assert "orange" in myfruits #Raises AssertionError (known)
except AssertionError:
# handle assertion
raise
except Exception:
# handle everything
It's more precise because if the unknown exception raised by FruitFunction() happens to be AssertionError then it won't get caught in the inner try. Without separating the statements, there's no (sensible) way to distinguish two exceptions of the same type thrown from the two different places. So with the first code you'd better hope that FruitFunction() either doesn't raise AssertionError, or that if it does then it can be handled the same way as the other one.
try:
# Do something
myurl = urllib.urlopen(parametes)
assert myurl.status == 202
except Exception as e:
# Handle Exception
print('An error occured')
if isinstance(e, AssertionError):
# Handle AssertionError
print('it was something serious too!')
else:
# proceed normal stuff
In the case that it's both raised an unknown exception and an AssertionError, and you need to handle both, you should use two separate try statements.
try:
raise IndexError()
assert 'orange' in myfruits
except AssertionError:
print 'AssertionError'
except:
print 'another error'
The above will only catch the first error, while
try:
raise IndexError()
except:
print 'another error'
try:
assert 'orange' in myfruits
except AssertionError:
print 'AssertionError'
Will catch both errors.
Related
I am facing a problem while catching the exception in my unitest code.
Following is my code
def get_param(param)
if param is None:
raise ValueError('param is not set')
def test_param():
with pytest.raises(ValueError) as e:
get_param()
The problem is that when function does not raise exception, test_param() gets fail with the following error.
Failed: DID NOT RAISE <class 'ValueError'>
It works as expected when get_param(param) function throws exception.
I have faced same problem. This solutions works for me.
try:
with pytest.raises(ValidationError) as excinfo:
validate_bank_account_number(value=value)
assert excinfo.value.args[0] == 'your_error_message_returned_from_validation_error'
except:
assert True
It's not a problem, python.raises works as expected. By using it you're asserting a certain exception.
If you really don't want to get the exception, you can use try-except to catch and suppress it like this:
from _pytest.outcomes import Failed
def test_param():
try:
with pytest.raises(ValueError):
get_param()
except Failed as exc:
# suppress
pass
# or
# do something else with the exception
print(exc)
# or
raise SomeOtherException
I am curious if there is a way in python to continue on within try/catch block, after you catch an exception, look at its properties, and if not relevant, then continue down the stack.
try:
# Code
except AppleError as apple_ex:
# look at 'apple_ex.error_code' error body, and if not relevant,
# continue on to next down the catch block...
# In other words, proceed to except BananaError and so on down.
except BananaError as banana_ex:
# ...
except Exception as ex:
# ...
That is not how exceptions are handled in Python. When you raise an exception in a try block, if you handle catching it in the except, it will fall inside that block, but will not continue to the next except at that same level. Observe this functional example:
try:
raise AttributeError()
except AttributeError:
raise TypeError()
except TypeError:
print("it got caught") # will not catch the TypeError raised above
So, in your try, we raise an AttributeError, we catch it, and then raise a TypeError inside catching the AttributeError.
The except TypeError will not catch that TypeError.
Based on how you are explaining your problem, you need to rethink how you are handling your exceptions and see if you can determine the handling of errors somewhere else, and raise the error there.
For example:
def some_func():
try:
thing()
except SomeException:
# analyze the exception here and raise the error you *should* raise
if apple_error_thing:
raise AppleError
elif banana_error_thing:
raise BananaError
else:
raise UnknownException
def your_func():
try:
some_func()
except AppleError as e:
print('Apple')
except BananaError as e:
print('Banana')
except UnknownException as e:
print('Unknown')
An AppleError is still an AppleError and not a BananaError, even if error_code is not relevant, so it makes no sense to fall through to BananaError.
You could instead define specific errors for your different error codes:
GRANNY_SMITH_ERROR = 1
MACINTOSH_ERROR = 2
class AppleError(Exception):
def __init__(self, error_code, *args):
super(AppleError, self).__init__(*args)
self.error_code = error_code
class GrannySmithError(AppleError):
def __init__(self, *args):
super(GrannySmithError, self).__init__(GRANNY_SMITH_ERROR, *args)
class MacintoshError(AppleError):
def __init__(self, *args):
super(MacintoshError, self).__init__(MACINTOSH_ERROR, *args)
Then you can try to match the specific error:
try: raise MacintoshError()
except MacintoshError as exc: print("mac")
except GrannySmithError as exc: print("granny smith")
If you do not care to distinguish between different types of apple errors, you can still trap all apple errors:
try: raise MacintoshError()
except AppleError as exc: print("generic apple")
You can combine these, for example, only doing special processing for GrannySmith, not for Macintosh:
try: raise MacintoshError()
except GrannySmithError as exc: print("granny smith")
except AppleError as exc: print("generic apple")
The important thing is to list the errors from most specific to least specific. If you test for AppleError before GrannySmithError, then it will never enter the GrannySmith block.
No, that isn't possible. After the exception is handled by the inner except it doesn't have the ability to get handled by the outer except:
From the docs on the try statement:
When the end of this block is reached, execution continues normally after the entire try statement. (This means that if two nested handlers exist for the same exception, and the exception occurs in the try clause of the inner handler, the outer handler will not handle the exception.)
In short your only solution might be to have another handler at an outer level and re-raise the exception in the inner handler, that is:
try:
try:
raise ZeroDivisionError
except ZeroDivisionError as e:
print("caught")
raise ZeroDivisionError
except ZeroDivisionError as f:
print("caught")
Now the nested except raises an exception which is consequently caught by a similar handler.
I'm trying to do a nested try/catch block in Python to print some extra debugging information:
try:
assert( False )
except:
print "some debugging information"
try:
another_function()
except:
print "that didn't work either"
else:
print "ooh, that worked!"
raise
I'd like to always re-raise the first error, but this code appears to raise the second error (the one caught with "that didn't work either"). Is there a way to re-raise the first exception?
raise, with no arguments, raises the last exception. To get the behavior you want, put the error in a variable so that you can raise with that exception instead:
try:
assert( False )
# Right here
except Exception as e:
print "some debugging information"
try:
another_function()
except:
print "that didn't work either"
else:
print "ooh, that worked!"
raise e
Note however that you should capture for a more specific exception rather than just Exception.
You should capture the first Exception in a variable.
try:
assert(False)
except Exception as e:
print "some debugging information"
try:
another_function()
except:
print "that didn't work either"
else:
print "ooh, that worked!"
raise e
raise by default will raise the last Exception.
raise raises the last exception caught unless you specify otherwise. If you want to reraise an early exception, you have to bind it to a name for later reference.
In Python 2.x:
try:
assert False
except Exception, e:
...
raise e
In Python 3.x:
try:
assert False
except Exception as e:
...
raise e
Unless you are writing general purpose code, you want to catch only the exceptions you are prepared to deal with... so in the above example you would write:
except AssertionError ... :
How to handle all but one exception?
try:
something
except <any Exception except for a NoChildException>:
# handling
Something like this, except without destroying the original traceback:
try:
something
except NoChildException:
raise NoChildException
except Exception:
# handling
The answer is to simply do a bare raise:
try:
...
except NoChildException:
# optionally, do some stuff here and then ...
raise
except Exception:
# handling
This will re-raise the last thrown exception, with original stack trace intact (even if it's been handled!).
New to Python ... but is not this a viable answer?
I use it and apparently works.... and is linear.
try:
something
except NoChildException:
assert True
except Exception:
# handling
E.g., I use this to get rid of (in certain situation useless) return exception FileExistsError from os.mkdir.
That is my code is:
try:
os.mkdir(dbFileDir, mode=0o700)
except FileExistsError:
assert True
and I simply accept as an abort to execution the fact that the dir is not somehow accessible.
I'd offer this as an improvement on the accepted answer.
try:
dosomestuff()
except MySpecialException:
ttype, value, traceback = sys.exc_info()
raise ttype, value, traceback
except Exception as e:
mse = convert_to_myspecialexception_with_local_context(e, context)
raise mse
This approach improves on the accepted answer by maintaining the original stacktrace when MySpecialException is caught, so when your top-level exception handler logs the exception you'll get a traceback that points to where the original exception was thrown.
You can do type checking on exceptions! Simply write
try:
...
except Exception as e:
if type(e) == NoChildException:
raise
It still includes the original stack trace.
I found a context in which catching all errors but one is not a bad thing, namely unit testing.
If I have a method:
def my_method():
try:
something()
except IOError, e:
handle_it()
Then it could plausibly have a unit test that looks like:
def test_my_method():
try:
my_module.my_method()
except IOError, e:
print "shouldn't see this error message"
assert False
except Exception, e:
print "some other error message"
assert False
assert True
Because you have now detected that my_method just threw an unexpected 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'...
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.
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.
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