Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Applescript have an "exit" or "die" command similar to PHP?

How can I throw an error and exit in Applescript? I'd like to have something like PHP's die or exit command so that the "completed" dialog does not fire.

function1()
display dialog "completed"

on function1()
    function2()
end function1

on function2()
    exit //what do i use here?
end function2

Here is what I've tried with the answer that was posted below:

function1()
display dialog "completed"

on function1()
    function2()
end function1

on function2()

    try
        display dialog "Do you want to catch an error?" buttons {"Continue without error", "Cause an error"} default button 2
        if button returned of result is "Cause an error" then
            error "I'm causing an error and thus it is caught in 'on error'"
        end if
        display dialog "completed without error"
    on error theError
        return theError -- this ends the applescript when an error occurs
    end try


end function2
like image 598
cwd Avatar asked Nov 16 '11 19:11

cwd


1 Answers

Try this ;)

-- errors are only handled inside of a "try" block of code
try
    display dialog "Do you want to catch an error?" buttons {"Continue without error", "Cause an error"} default button 2
    if button returned of result is "Cause an error" then
        error "I'm causing an error and thus it is caught in 'on error'"
    end if
    display dialog "completed without error"
on error theError
    return theError -- this ends the applescript when an error occurs
end try

EDIT: Based on your comment... just return values from your functions. Check that returned value in your main code where you call the functions and the return value will tell you if you should "quit" the application or not. As such here's one way to solve your example problem...

set returnValue to function1()

-- we check the return value from the handler
if returnValue is not true then return -- this "quits" the script

display dialog "completed"

on function1()
    set returnValue to function2()
    return returnValue
end function1

-- note that when there is no error the the script returns true.
-- so we can check for that and actt appropriately in the main script
on function2()
    try
        display dialog "Do you want to catch an error?" buttons {"Continue without error", "Cause an error"} default button 2
        if button returned of result is "Cause an error" then
            error "I'm causing an error and thus it is caught in 'on error'"
        end if
        display dialog "completed without error"
        return true
    on error theError
        return theError -- this ends the applescript when an error occurs
    end try
end function2
like image 91
regulus6633 Avatar answered Oct 05 '22 03:10

regulus6633