Why doesn't it go into on error

Hello,

I f enter a real number, the on error is not triggered. Why?

Thanks for the reply.


set correctEntry to false

repeat while correctEntry is false
	
	set textToDisplay to "How often has the sentence to be repeated?"
	
	display dialog textToDisplay default answer "2"
	set valueEntered to text returned of the result
	
	try
		
		set valueEntered to valueEntered as integer
		set correctEntry to true
		
	on error
		
		try
			
			set valueEntered to valueEntered as number
			display dialog "You entered a fractional number insread of an integer."
			
		on error
			
			display dialog "Instead of an integer, like 9, you entered text."
			
		end try
		
		
	end try
	
end repeat

repeat valueEntered times
	say "Julia is a beautiful actress"
end repeat

That’s how AS works:

1.5 as integer --> 2

The workaround is to coerce to a number and check its class:

set x to valueEntered as number
if class of x is real then
	-- show dialog

Just run this code:

"1,5" as integer --use 1.5 for English

You’ll see that it returns 2 and not an error is thrown. When you use 1.5 it will return 15 because the period is an thousand separator. These coercions are done for you without throwing an error and should be considered as an feature. To be sure an entered value is an integer you could use something like:

set isInteger to ((givenText as integer) as string)'s length = length of givenText

Edit: I would go for Shane’s solution above!

One man’s feature is another’s annoyance :|. The rounding and coercion of reals with no-zero fractional parts was only introduced in OS X 10.3 (OK, a long time ago now), and it broke quite a few scripts at the time.