AlSub
AlSub

Reputation: 1155

invalid syntax for raising an exception inside a class method

I am trying to raise an AttributeError inside a class-method, the idea of this method is that if apply_button is None then apply the exception, else click on the button.

However when I do the following code:

import pyautogui
import os

def apply_button_detector(self):
        
    apply_button=pyautogui.locateOnScreen(os.path.join(ROOT_DIR, r'apply_button.png'), region=(1, 300, 500, 700))
           
    if apply_button is None:
        try:
           print('no apply button')
           raise AttributeError()
                            
    else:
          # click on Apply button
           apply_button_location=pyautogui.center(apply_button)
           pyautogui.click(apply_button_location)

It marks me an error at raise AttributeError():

invalid syntax ()

How could I adjust the function in order to return an AttributeError?

Upvotes: 0

Views: 38

Answers (1)

tdelaney
tdelaney

Reputation: 77347

You've put the raise inside a try block, but tries need exception handlers. That's what try is for - to demark the code that will be handled by one or more except or finally handlers. Just remove the try. Also, since the raise interrupts current execution, there is no reason to have an else for the remaining code. Its more readable to just leave that part out. Finally, the print seems a bit odd because the raise has the information you need. I moved the informational message there.

import pyautogui
import os

def apply_button_detector(self):
        
    apply_button=pyautogui.locateOnScreen(os.path.join(ROOT_DIR, r'apply_button.png'), region=(1, 300, 500, 700))
           
    if apply_button is None:
         raise AttributeError('no apply button')
    # click on Apply button
    apply_button_location=pyautogui.center(apply_button)
    pyautogui.click(apply_button_location)

Upvotes: 1

Related Questions