What is the difference between Try/Catch and OnError()? When to use one or the other?

Get help with using AutoHotkey (v1.1 and older) and its commands and hotkeys
Groot
Posts: 22
Joined: 28 Feb 2019, 10:51

What is the difference between Try/Catch and OnError()? When to use one or the other?

Post by Groot » 20 Jun 2021, 08:32

Hi friends,

I am currently writing a script that reads and writes files.
I would like to handle the possible I/O errors,
but the doc isn't clear to me regarding wether I should use Try/Catch or OnError().

And more generally, what is the difference between the two? And when to use one or the other?

Thank you!

User avatar
boiler
Posts: 16705
Joined: 21 Dec 2014, 02:44

Re: What is the difference between Try/Catch and OnError()? When to use one or the other?

Post by boiler » 20 Jun 2021, 08:35

When you use Try, you are identifying specifically which lines of code over which it is applicable rather than just any unhandled error like OnError(). That should answer both questions.

Groot
Posts: 22
Joined: 28 Feb 2019, 10:51

Re: What is the difference between Try/Catch and OnError()? When to use one or the other?

Post by Groot » 20 Jun 2021, 12:37

Hi boiler,

That's a good point, thank you.

But let's say I put the whole code of my function in a huge Try/Catch.
What would be the difference with using OnError() then?

User avatar
boiler
Posts: 16705
Joined: 21 Dec 2014, 02:44

Re: What is the difference between Try/Catch and OnError()? When to use one or the other?

Post by boiler » 20 Jun 2021, 13:15

The differences would be in how the errors can be handled between Catch/Finally and OnError(). Visit the links to see the details.

swagfag
Posts: 6222
Joined: 11 Jan 2017, 17:59

Re: What is the difference between Try/Catch and OnError()? When to use one or the other?

Post by swagfag » 20 Jun 2021, 13:24

u can have multiple OnError() handlers active at a time
an OnError() handler can decide whether to proceed running the thread or exit it once a thrown exception has been emitted
in v1 specifically(not the case in v2), most built-in commands dont throw exceptions unless ran inside a try-block(and even so u have to actually check with the docs whether they do), so ur OnError() handlers wont ever get triggered
the huge Try/Catch wouldnt allow u, for example if u wrapped 5 commands and the 2nd one threw, to proceed with the execution from the 3rd after doing something in the Catch-block

Groot
Posts: 22
Joined: 28 Feb 2019, 10:51

Re: What is the difference between Try/Catch and OnError()? When to use one or the other?

Post by Groot » 20 Jun 2021, 14:24

Thank you swagfag. I get it now!

Post Reply

Return to “Ask for Help (v1)”