Need an example of how to use "try" and "catch"

Bob Sneidar bobs at twft.com
Fri Mar 23 13:52:10 EDT 2012


Look up "throw" in the dictionary. Apparently you can use it with or without a try/catch structure. It's a way to generate an error outside the scope of engine generated script errors. 

try
   if not (there is a file "/Users/MyProfile/Library/Preferences/MyAppCriticalPreferences.plist") then
      throw "missing_prefs_file"
   end if
catch theError
   answer theError & cr & "I have to quit now."
   quit
end try

I know it works because I just accidentally quit my Livecode session!

This could be used in conjunction with a central error handling user defined command or function. Let's say you have a command called "on customError pErrorNum". In it you have a switch statement for pErrorNum which handles each error differently. Some errors you want to simply inform the user and reset the form. Others may be critical ones and you have to bail out gracefully. 

try
   if not (there is a file "/Users/MyProfile/Library/Preferences/MyAppCriticalPreferences.plist") then
      throw "missing_prefs_file"
   end if
catch theError
   customError -666
end try

on customError pErrorNum
   switch pErrorNum
      case 666
         put "A critical error has occurred. The application will now exit." into theMsg
         put true into isCritical
      case 777
         put "A non-critical error has occurred. Please try again."
         put false into isCritical
   end switch

   answer theMsg as sheet

   if isCritical then
      cleanup -- I am not going to write a fictitious cleanup routine!      
      quit
   end if
end customError

Bob


On Mar 23, 2012, at 10:08 AM, Jim Hurley wrote:

> Mark,
> 
> Yes! I agree with you about "throw". 
> 
> Do you,  or dose anyone, have an example that shows the use of the "throw" command in conjunction with the "try-catch" structure?
> 
> Jim





More information about the use-livecode mailing list