Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Caught exception is None

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.

like image 330
Etse Avatar asked Aug 18 '14 20:08

Etse


People also ask

What happen if exception is not caught?

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.

What is caught exception?

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 .

What happens when we throw exception?

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.

How do you reraise the current exception?

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.


2 Answers

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
like image 137
Daniel Avatar answered Oct 14 '22 07:10

Daniel


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))
like image 27
Jon Clements Avatar answered Oct 14 '22 06:10

Jon Clements