using Exception

Get help with using AutoHotkey (v1.1 and older) and its commands and hotkeys
User avatar
jeeswg
Posts: 6902
Joined: 19 Dec 2016, 01:58
Location: UK

using Exception

22 Jul 2017, 02:32

Is this how Exception was intended to be used? Or one intended way?

Code: Select all

;[Throw and Exception]
;Throw
;https://autohotkey.com/docs/commands/Throw.htm

q::
vNum1 := 1, vNum2 := 2
MsgBox, % Add1(vNum1, vNum2)
vNum1 := 1, vNum2 := ""
MsgBox, % Add1(vNum1, vNum2)
return

w::
vNum1 := 1, vNum2 := 2
MsgBox, % Add2(vNum1, vNum2)
vNum1 := 1, vNum2 := ""
MsgBox, % Add2(vNum1, vNum2)
return

Add1(vNum1, vNum2)
{
	vRet := vNum1 + vNum2
	if (vRet = "")
	{
		MsgBox, % "error: non-numeric"
		Exit
	}
	return vRet
}

Add2(vNum1, vNum2)
{
	vRet := vNum1 + vNum2
	if (vRet = "")
		throw Exception("error: non-numeric")
	return vRet
}

Code: Select all

;i.e. as a code line-saver, that also gives more ominous 'clearly an error that exits the thread' error messages
	if (vRet = "")
	{
		MsgBox, % "error: non-numeric"
		Exit
	}

	if (vRet = "")
		throw Exception("error: non-numeric")
==================================================

Another example:

Code: Select all

q::
w::
e::
r::
if InStr(A_ThisHotkey, "q")
	throw Exception("ERROR 1: " A_ThisHotkey)
if InStr(A_ThisHotkey, "w")
	throw Exception("ERROR 2: " A_ThisHotkey)
if InStr(A_ThisHotkey, "e")
	throw Exception("ERROR 3: " A_ThisHotkey)
MsgBox, % "hello"
return
Although errors that stop the current script from reloading (keeping the current script running instead), that exit the thread, and that exit AutoHotkey altogether, can look similar, causing confusion, so perhaps a standard MsgBox is preferable.
homepage | tutorials | wish list | fun threads | donate
WARNING: copy your posts/messages before hitting Submit as you may lose them due to CAPTCHA
User avatar
AlphaBravo
Posts: 586
Joined: 29 Sep 2013, 22:59

Re: using Exception

22 Jul 2017, 12:16

good examples of using Exception : try
I also use it as a flow track like so

Code: Select all

a::gosub x
b::gosub z

x:
gosub y
return

y:
gosub z
return

c::
z:
trail := ""
while Exception("", 0-A_Index).what <> 0-A_Index
	trail := Exception("",0-A_Index).what  " > "  trail
ToolTip % Trim(trail, " >") 
return
pressing a, b or c will end up at subroutine "z" but through different flow of execution, sometimes you need to know how reached here.

Return to “Ask for Help (v1)”

Who is online

Users browsing this forum: ntepa, vanove and 180 guests