How To Catch PyGetWindowException When Using Pygetwindow In Python?
Solution 1:
You should have import pygetwindow
at the begging of your script. It complains about not knowing what pygetwindow
is.
Solution 2:
Update
From the source file, it was clear that in order to use PyGetWindowException
, you need to import the exception specifically (and not just import pygetwindow
). Therefore, in order to catch the exception, one will have to do:
from pygetwindow import PyGetWindowException
After this import, you can use the exception in the normal way:
try:
#implementation
except PyGetWindowException:
#handle exception
Update 2
Another general way to do this would be to get the exception name from general exception and compare.
try:
try:
#implementation
except Exception as e:
if e.__class__.__name__ == 'PyGetWindowException':
#handle exception
else:
raise e
except Exception as e:
#handle other exceptions except pygetwindow exception
Original answer (not recommended)
Found a way to solve this question in this answer.
From the source of pygetwindow
, it was clear that, whenever PyGetWindowException
is raised, it is accompanied by the text:
"Error code from Windows:"
which indicates the error code given by Windows.
Based on this information, I did the following:
try:
try:
#Implementation
except Exception as e:
if "Error code from Windows" in str(e)
# Handle pygetwindow exception
else:
raise e
except Exception as e:
#handle other exceptions
This is another way (although the first one and second one are the correct and straightforward solutions) to solve the problem.
Post a Comment for "How To Catch PyGetWindowException When Using Pygetwindow In Python?"