Recently I was fighting with a scenario where I was throwing an exception but couldn’t figure out why the exception was actually happening. I’ve created a much simpler example below to demonstrate what I learned during the process of solving this.
The simplified scenario is as follows: I have a Python Module that calls another module to do some work that is wrapped in a try/except. Code is shown below.
Here’s the problem: when I run the code, I throw the catch-all exception, but no details are available as to the reason why it is failing. In my real world situation, it caused a lot of head scratching as during my troubleshooting there was no obvious cause.
If I was to remove the Try/Except statement, then I get a nice stacktrace that tells me what you’ve probably already figured out, that my import statement is commented out, so the time module isn’t available when I’m calling it. However, that’s not a real world solution, so how I can get the stacktrace inside of a Try/Except?
Enter the Traceback Module! Using this module, you can surface up these stacktraces in the last, generic except statement to find out what’s going on behind the scenes!
Now, when I run the program, I get a very helpful error: