Exceptions are unwanted errors that occur during run time. They can be avoided using try command.
try
Let’s take a simple example to understand use of try first.
Script [11.1.1]:
beep
set x to 1 / 0
say "I cannot speak this"
Explanation: A beep will be played first. But an error will occur on creating variable x because 1/0 is not defined. Because of this, all the subsequent statements will not be executed.
Figure 11.1.1 Exception
However this can be avoided by using the try command.
Script [11.1.2]:
try
beep
set x to 1 / 0
say "I cannot speak this"
end try
say "Hey There"
Explanation: Here with the help of try command, a beep sound will be made and then variable x will be created. But because 1/0 is not defined an error will occur. And the try block will look for actions to be performed on error. But since nothing is mentioned, the execution will proceed from the commands outside the try block.
Let’s take another example. Here we will take age as input from the user. However the script will fail if the input is not a number. To handle this we will use the try command
Script [11.1.3]:
set temp to display dialog "Enter Age" default answer ""
set myAge to the text returned of temp
try
set myAge to myAge as number
display dialog myAge
on error
display dialog "Please enter a number"
end try
Explanation: In this example, I have asked user to enter his/her age. This input will be a String. However we need to make sure that the age is in number format. So I use a try block and perform coercion on myAge. If successful, then try block will display a dialog with myAge. If not successful then the on error commands will get executed.
Figure 11.1.3 Number Exception Check
What if when error occurs, I want to print the Error Message and Error Number.
Script [11.1.4]:
set temp to display dialog "Enter Age" default answer ""
set myAge to the text returned of temp
try
set myAge to myAge as number
display dialog myAge
on error the errorMessage number the errorNumber
display dialog "Error " & errorNumber & " : " & errorMessage
end try
Explanation: This is the same Script as 11.1.3. However there is minor change in the on error section. I have created variable errorMessage and errorNumber which store error message and error number respectively.
Note the declaration of the variables errorMessage and errorNumber.
Figure 11.1.4 Error Message & Number