Reputation: 426
In Pycharm I would like to, in debug mode, stop on any exception that enters my code but ignore any exceptions that are thrown and caught by library functions.
Pycharm has an option in breakpoints called Any Exception where you can say "On Raise" and "Ignore library files" which goes a long way but it does not ignore StopIteration and ExitGenerator, which means it stops at the end of any of your generator or yield statements.
eg in the code below the generator next((x for x in a_list))
throws an ExitGenerator exception which Pycharm stops on in debug mode, but this is actually caught and handled by libary code so I want to ignore it.
See for example this program
import pandas as pd
try:
# spurious exception
a_list = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
first_item = next((x for x in a_list))
print(f'first item = {first_item}')
except Exception as e:
# the program won't go here as the ExitGenerator exception is handled by the standard library
print(f'got exception from generator : {str(e)}')
try:
# proper exception from a library
df = pd.DataFrame(index=[1, 2, 3], data=['a', 'b', 'c'], columns=['letters'])
# try to access but use the wrong column name to generate an exception
print(df['non_existent_column'])
except Exception as e:
# the program will come here as the code tried to access a non-existent column
print(f'got exception from pandas : {str(e)}')
and that produces the follow output in debug
Connected to pydev debugger (build 201.6668.115)
Stack:
<genexpr>, play.py:6
<module>, play.py:6
first item = a
Stack:
<module>, play.py:17
got exception from pandas : 'non_existent_column'
Process finished with exit code 0
Pycharm is first catching the spurious generator exception that does not reach my code and then catching the proper pandas exception which does read my code. This is my breakpoint setting btw
Also this from a few years ago seems to be related Break on all exceptions except if it is stop iteration or Generator Exit
suggests it might have been solved but it don't know how to enable it.
Upvotes: 9
Views: 1571
Reputation: 426
Update
I've managed to get something working based on some answers here get-last-exception-in-pdb
If I add this to the Pycharm condition it avoids ignores StopIteration and ExitGenerator
not (isinstance(__exception__ , tuple) and len(__exception__)>=1 and __exception__[0] in [StopIteration, GeneratorExit])
Upvotes: 18