<h3>更新</h3>
<p>从<a href="https://github.com/asweigart/PyGetWindow/tree/be242794b08e0d30b27502610c97c8a1640b4e20/src/pygetwindow" rel="nofollow noreferrer">source</a>文件可以清楚地看出,为了使用<code>PyGetWindowException</code>,您需要专门导入异常(而不仅仅是<code>import pygetwindow</code>)。因此,为了捕获异常,必须执行以下操作:</p>
<pre><code>from pygetwindow import PyGetWindowException
</code></pre>
<p>导入后,您可以按正常方式使用异常:</p>
<pre><code>try:
#implementation
except PyGetWindowException:
#handle exception
</code></pre>
<h3>更新2</h3>
<p>另一种通用的方法是从通用异常中<a href="https://stackoverflow.com/questions/18176602/how-to-get-the-name-of-an-exception-that-was-caught-in-python">get the exception name</a>并进行比较</p>
<pre><code>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
</code></pre>
<h3>原始答案(不推荐)</h3>
<p>在这个<a href="https://stackoverflow.com/a/45735326/10153731">answer</a>中找到了解决这个问题的方法</p>
<p>从{<cd3>}的{a1}可以清楚地看出,每当提出{<cd1>}时,都会伴随着以下文本:</p>
<blockquote>
<p>"Error code from Windows:"</p>
</blockquote>
<p>它指示Windows提供的错误代码</p>
<p>根据这些信息,我做了以下工作:</p>
<pre><code>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
</code></pre>
<p>这是解决问题的另一种方法(尽管第一种和第二种方法是正确和直接的解决方案)</p>