Try/Catch VS Element exists activity

Hello everyone,
Why using Try/Catch is more effective way than using element exists activity to handle the click on a UI element that is not always available?

regards…

So there is nuance here.

For example if you want to check if an element exists, getting a false value when it doesn’t might not actually really help you debug the issue later, you just know the element could not be found.

Using a click in a try catch you can get the error from the Click event which explains which part of the selector didn’t match and shows some close matches, this can be huge in debugging and help you find a bad selector without even needing to re-run a bot.

That being said, many developers who do the try catch also don’t use the exception they catch and also throw a generic error, this also makes debugging harder as you sometimes have to do some real deep dives to see the real error thrown (which may not be a SelectorNotFound).
I find this is often due to developers who are just ‘scared’ of a ‘technical’ looking error message and want to make one that looks more ‘friendly’. I think this is a bad choice.

I also find developers who use an element exists before a click are also just scared of a ‘technical’ looking error message and then throw their own generic error saying ‘Click failed’ or something, which again I think is a bad choice.

Question is why do you want to catch it and what do you want to do with the error?

I personally don’t put a catch around any of my click events and do any handling, as whats the point, the original error is clear.

I feel there absolutely is room for a try catch to catch a selector not found exception in certain circumstances, for example to use the exception as an inner exception on another one that is thrown, that can be very powerful to give a ‘clearer’ error but not lose the technical detail of the selector not found exception.

2 Likes

Hi @esraa_elzoghby,

for Try-Catch vs Element exist

It would not be correct to say that they are better than each other.If you know the next screen you will encounter, you should use element exist. But if you don’t know what’s coming and you need a control mechanism you can use try catch.

Regards,
MY

1 Like

I suggest you re-read the question Muhammed.
The poster is not interested in the ‘next screen’. The question was clearly directed as a click activity on a element that is not always available.

Hi @Jon_Smith, Thanks for the fix.

It’s not more effective. Which way you do things depends on your goal.

1 Like

Thanks, I got your answer.

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.