Using Err programmatically

New to FreeBASIC? Post your questions here.
Post Reply
GWBASICcoder
Posts: 21
Joined: Jul 29, 2022 12:43

Using Err programmatically

Post by GWBASICcoder »

Hi,

I would like to use the Err function and statement to generate an error flag
and handle the error afterwards.

In the code below, I have set err to 1009 whenever an erroneous input is
received. However, this doesn't see to work, as err() always returns 0.
I don't want to use the On Error type handler.

Code: Select all

function repeatstr(s as string) as string
	err = 0
	if s = "a" then
		err = 1009
	end if
	
	return s & s
end function

print "repeat = "; repeatstr("s")
print "error = "; err()

print "repeat = "; repeatstr("a")
print "error = "; err()

Code: Select all

repeat = ss
error =  0
repeat = aa
error =  0
Thanks in advance.
fxm
Moderator
Posts: 12081
Joined: Apr 22, 2009 12:46
Location: Paris suburbs, FRANCE

Re: Using Err programmatically

Post by fxm »

Some internal functions will reset the error value with its own error status.
To preserve your error status, use your own global variable of error:

Code: Select all

dim shared as long myerr

function repeatstr(s as string) as string
	myerr = 0
	if s = "a" then
		myerr = 1009
	end if
	
	return s & s
end function

print "repeat = "; repeatstr("s")
print "error = "; myerr

print "repeat = "; repeatstr("a")
print "error = "; myerr
dodicat
Posts: 7976
Joined: Jan 10, 2006 20:30
Location: Scotland

Re: Using Err programmatically

Post by dodicat »

Better not to print err directly, instead use a variable.
From the help file:
Note: Care should be taken when calling an internal function (such as Print) after an error occurred, because it will reset the error value with its own error status. To preserve the Err value, it is a good idea to store it in a variable as soon as the error handler is entered.

Your example again:

Code: Select all


function repeatstr(s as string) as string
	err = 0
	if s = "a" then
       
		err = 1009
	end if
    var e=err
	
	return s & s & "  error =  "&e
end function

print "repeat = "; repeatstr("s")
'print "error = "; err()

print "repeat = "; repeatstr("a")
'print "error = "; err()

sleep
 
Post Reply