D. E. Scioli
D. E. Scioli

Reputation: 55

Python PyAutoGUI return "ImageNotFoundException", but "except" doesn't recognise it as an exception

With the previous version of pyautogui, when an image wasn't found the return was "None", so I used to handle it with except TypeError:. But since the update (version 0.9.41), it isn't working, as it's returning ImageNotFoundException, but it isn't recognised as an exception. When I try to do except ImageNotFoundException: it gives the error:

[E0712] Catching an exception which doesn't inherit from Exception: ImageNotFoundException

How should this error be handled?

Upvotes: 4

Views: 28672

Answers (3)

Gibrel
Gibrel

Reputation: 1

Just force pyautogui to use ImageNotFoundException. Use this line when initializing pyautogui:

pyautogui.useImageNotFoundException()

Do not use pyscreeze's ImageNotFoundException. As we can see on class ImageNotFoundException definition, the developer points out it's not an ideal use:

class ImageNotFoundException(PyAutoGUIException):
"""
This exception is the PyAutoGUI version of PyScreeze's `ImageNotFoundException`, which is raised when a locate*()
function call is unable to find an image.

Ideally, `pyscreeze.ImageNotFoundException` should never be raised by PyAutoGUI.
"""

Upvotes: 0

Daishi
Daishi

Reputation: 14289

This works fine with pyautogui 0.9.52 and python 3.9.0

import pyautogui

# force use of ImageNotFoundException
pyautogui.useImageNotFoundException()

try:
    location = pyautogui.locateOnScreen('foo.png')
    print('image found')
except pyautogui.ImageNotFoundException:
    print('ImageNotFoundException: image not found')

I found the useImageNotFoundException() part in this page locateCenterOnScreen doesn't raise ImageNotFoundException. · Issue #441 · asweigart/pyautogui. If useImageNotFoundException() is not called, locateOnScreen() just returns None.

Upvotes: 10

SL8
SL8

Reputation: 29

I had the same problem as you, and also couldn't figure out why handling this with an except wasn't possible. Now I have figured it out on python 3.7, this should work if you've installed the PyScreeze package: from pyscreeze import ImageNotFoundException

I hope it can help you out :)

Upvotes: 2

Related Questions