some_function() raises an exception while executing, so the program jumps to the except:
try:
some_function()
except:
print("exception happened!")
How do I see what caused the exception to occur?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The other answers all point out that you should not catch generic exceptions, but no one seems to want to tell you why, which is essential to understanding when you can break the “rule”. Here is an explanation. Basically, it’s so that you don’t hide:
So as long as you take care to do none of those things, it’s OK to catch the generic exception. For instance, you could provide information about the exception to the user another way, like:
So how to catch the generic exception? There are several ways. If you just want the exception object, do it like this:
Make sure
messageis brought to the attention of the user in a hard-to-miss way! Printing it, as shown above, may not be enough if the message is buried in lots of other messages. Failing to get the users attention is tantamount to swallowing all exceptions, and if there’s one impression you should have come away with after reading the answers on this page, it’s that this is not a good thing. Ending the except block with araisestatement will remedy the problem by transparently reraising the exception that was caught.The difference between the above and using just
except:without any argument is twofold:except:doesn’t give you the exception object to inspectSystemExit,KeyboardInterruptandGeneratorExitaren’t caught by the above code, which is generally what you want. See the exception hierarchy.If you also want the same stacktrace you get if you do not catch the exception, you can get that like this (still inside the except clause):
If you use the
loggingmodule, you can print the exception to the log (along with a message) like this:If you want to dig deeper and examine the stack, look at variables etc., use the
post_mortemfunction of thepdbmodule inside the except block:I’ve found this last method to be invaluable when hunting down bugs.