I have a script written in python2.7 where I, for debugging purposes, use a catch-all statement to catch and print all exceptions. For some reason, the exception caught is sometimes None
. What could cause this to happen?
the code is something like this:
from __future__ import print_function
try:
run_arbitrary_code()
except Exception as e:
print(e)
The output is then:
None
None
None
None
I have never experienced an exception being None
, and wonder what could cause this.
To answer some of the comments, the function does quite a lot. It includes things like graph searches and sending and receiving JSON data over a socket, so there are quite a few things that could go wrong. But the issue here is that the raised exception is None
, which does not help my debugging at all.
What happens if an exception is not caught? If an exception is not caught (with a catch block), the runtime system will abort the program (i.e. crash) and an exception message will print to the console.
Each catch block is an exception handler that handles the type of exception indicated by its argument. The argument type, ExceptionType , declares the type of exception that the handler can handle and must be the name of a class that inherits from the Throwable class. The handler can refer to the exception with name .
When an exception is thrown using the throw keyword, the flow of execution of the program is stopped and the control is transferred to the nearest enclosing try-catch block that matches the type of exception thrown. If no such match is found, the default exception handler terminates the program.
Reraise the current exception If you pass zero to the second argument of the division() function, the ZeroDivisionError exception will occur. However, instead of handling the exception, you can log the exception and raise it again. Note that you don't need to specify the exception object in the raise statement.
Look at the type of the exception, I bet it's a KeyError:
try:
dict()[None]
except Exception as e:
print(type(e), e)
Output:
<class 'KeyError'> None
You're better off printing the repr
of the exception, not the default str
that print
applies, eg:
from __future__ import print_function
try:
run_arbitrary_code()
except Exception as e:
print(repr(e))
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