I want to handle a specific exception in a certain way, and generically log all the others.
This is what I have:
class MyCustomException(Exception): pass
try:
something()
except MyCustomException:
something_custom()
except Exception as e:
#all others
logging.error("{}".format(e))
The problem is that even MyCustomException will be logged because it inherits from Exception. What can I do to avoid that?
What else is going on in your code?
MyCustomException should be checked and handled before flow ever gets to the second except clause
In [1]: def test():
...: try:
...: raise ValueError()
...: except ValueError:
...: print('valueerror')
...: except Exception:
...: print('exception')
...:
In [2]: test()
valueerror
In [3]: issubclass(ValueError,Exception)
Out[3]: True
Only the first matching except block will be executed:
class X(Exception): pass
try:
raise X
except X:
print 1
except Exception:
print 2
only prints 1.
Even if you raise an exception in an except block, it won't be caught by the other except blocks:
class X(Exception): pass
try:
raise X
except X:
print 1
0/0
except Exception:
print 2
prints 1 and raises ZeroDivisionError: integer division or modulo by zero
Related
Is there any way to raise multiple exceptions in python? In the following example, only the first exception is raised.
l = [0]
try:
1 / 0
except ZeroDivisionError as e:
raise Exception('zero division error') from e
try:
l[1]
except IndexError as e:
raise Exception('Index out of range') from e
Is there any other way?
Once an exception is raised and not catched, the execution of your program will stop. Hence, only one exception can be launched in such a simple script.
If you really want your program to raise multiple exceptions, you could however create a custom Exception representing multiple exceptions and launch it inside an except block. Example:
class ZeroDivAndIndexException(Exception):
"""Exception for Zero division and Index Out Of Bounds."""
I = [0]
try:
1 / I[0]
except ZeroDivisionError as e:
try:
I[1]
# Here you may raise Exception('zero division error')
except IndexError as e2:
raise ZeroDivAndIndexException()
Here my solution a bit long but seems to work :
class CustomError(Exception):
pass
l = [0]
exeps = []
try:
1 / 0
except ZeroDivisionError as e:
exeps.append(e)
try:
l[1]
except IndexError as e:
exeps.append(e)
if len(exeps)!=0:
[print(i.args[0]) for i in exeps]
raise CustomError("Multiple errors !!")
I tried to throw an exception with array data:
raise Exception([ValidateError.YEAR, row])
When I tried to catch it I get this error:
'Exception' object is not subscriptable
Code is:
except Exception as e:
#invalid
print(e[0])
To access the Exception arguments you passed as a list, you should use .args.
So, I believe you were looking for the following:
except Exception as e:
#valid
print(e.args[0][0])
As a side note, you can pass multiple arguments without them being in a list:
raise Exception(ValidateError.YEAR, row)
And then you need one index less:
except Exception as e:
#also valid
print(e.args[0])
You can subclass Exception and implement the __getitem__ function like so:
class MyException(Exception):
def __init__(self, l):
self.l = l
def __getitem__(self, key):
return self.l[key]
try:
raise MyException([1, 2, 3])
except MyException as e:
print(e[0])
running it:
python3 main.py
1
I'm trying to log some expected errors.
Initially, I wrote my script like:
except (BadZipFile, MemoryError) as e:
logger.error(f'No: {n} - {filename} = {e}')
But I noticed in the logger, only the BadZipFile error message seemed to make it. The MemoryError logs seemed to be blank after the = sign
I thought maybe the e was only storing the BadZipFile error message since it comes first, so I tried making a tuple:
except (BadZipFile, MemoryError) as (eb, em):
logger.error(f'No: {n} - {filename} = {eb, em}')
but of course the syntax is wrong. So what's going wrong with my code initially? Why is the MemoryError log not storing?
Whichever exception occurs first will get caught in except block. So, I think in your case 1st exception raising is BadZipFile. refer to #LMKR examples.
try to raise an exception explicitly to check whether it's working or not...
>>> try:
... if True:
... raise MemoryError("MemoryError occured")
... except (BadZipFile, MemoryError) as e:
... print(e)
Execution of program will be stopped when it occurs an exception and move to the except block. So when an exception occurred it is not possible to get another in the same try block. So will always receives one log of exception.
let me explain it with a bit of code, consider we have two types of errors, IndexError and ZeroDivisionError
Case1:
>>> l = []
>>> a = 1
>>> b = 0
>>> try:
... x = l[0]
... y = a/b
... except (IndexError, ZeroDivisionError) as e:
... print(e)
...
list index out of range
Case2:
>>> try:
... x = a/b
... y = l[0]
... except (IndexError, ZeroDivisionError) as e:
... print(e)
...
division by zero
Case3:
>>> try:
... x = l[0]/b
... except (IndexError, ZeroDivisionError) as e:
... print(e)
...
list index out of range
>>>
Case1, IndexError is raised first, so except bock is called with IndexError
Case2, ZeroDivisionError raised first, so except block is called with ZeroDivisionError
Case3, even though both exceptions are in single line line of execution happens from indexing so IndexError is raised.
EDIT:
In your case BadZipFile exception raised first, so your except block except (BadZipFile, MemoryError) as e: is called with BadZipFile exception. That's why your output is empty for MemoryError.
Even if MemoryError raised first with empty arguments then it will log nothing.
>>> try:
... raise MemoryError("This is memory error")
... except MemoryError as e:
... print(e)
...
This is memory error
>>> try:
... raise MemoryError()
... except MemoryError as e:
... print(e)
...
>>>
I wrote a function that needs to do 3 checks and if one of the tests fails it should return an exception of type of LookupError, but it doesn't work.
(*verify_checksum is another function)
def check_datagram(datagram, src_comp, dst_app):
try:
src_comp==datagram[0:16]
except LookupError:
return "Mismatch in src_comp"
try:
dst_app==datagram[40:48]
except LookupError:
return "Mismatch in dst_app"
try:
verify_checksum(datagram)
except False:
return "Wrong checksum"
return True
For example:
Input:
check_datagram("1111000000001111000011111111000001010101101010101111111111111111000000001111111100000000","0000111100001111", "11110000")
Expected output:
"Mismatch in dst_app"
def check_datagram(datagram, src_comp, dst_app):
if src_comp != datagram[0:16]:
raise LookupError("Mismatch in src_comp")
if dst_app != datagram[40:48]:
raise LookupError("Mismatch in dst_app")
if not verify_checksum(datagram):
raise LookupError("Wrong checksum")
return True # redundant?
With construction from NPE's answer you should use try..except there where you'll use declared check_datagram() function.
#python3
try:
check_datagram(a,b,c)
except LookupError as e:
print(str(e))
That allow you to get message from raised error.
Will this work?
try:
try:
field.value = filter(field.value, fields=self.fields, form=self, field=field)
except TypeError:
field.value = filter(field.value)
except ValidationError, e:
field.errors += e.args
field.value = revert
valid = False
break
Namely, if that first line throws a ValidationError, will the second except catch it?
I would have written it un-nested, but the second filter statement can fail too! And I want to use the same ValidationError block to catch that as well.
I'd test it myself, but this code is so interwoven now it's difficult to trip it properly :)
As a side note, is it bad to rely on it catching the TypeError and passing in only one arg instead? i.e., deliberately omitting some arguments where they aren't needed?
If the filter statement in the inner try raises an exception, it will first get checked against the inner set of "except" statements and then if none of those catch it, it will be checked against the outer set of "except" statements.
You can convince yourself this is the case just by doing something simple like this (this will only print "Caught the value error"):
try:
try:
raise ValueError('1')
except TypeError:
print 'Caught the type error'
except ValueError:
print 'Caught the value error!'
As another example, this one should print "Caught the inner ValueError" only:
try:
try:
raise ValueError('1')
except TypeError:
pass
except ValueError:
print 'Caught the inner ValueError!'
except ValueError:
print 'Caught the outer value error!'
To compliment Brent's answer, and test the other case:
class ValidationError(Exception): pass
def f(a): raise ValidationError()
try:
try:
f()
except TypeError:
f(1)
except ValidationError:
print 'caught1'
try:
try:
f(1)
except TypeError:
print 'oops'
except ValidationError:
print 'caught2'
Which prints:
caught1
caught2