Try

Guards one or more statements (functions or expressions) against runtime errors and exceptions thrown by the throw statement.

Try Statement
Try
{
    Statements
}

Remarks

The try statement is usually followed by a block - one or more statements (functions or expressions) enclosed in braces. If only a single statement is to be executed, it can be placed on the same line as try or on the next line, and the braces can be omitted. To specify code that executes only when try catches an error, use the catch statement.

An exception can be thrown by the throw statement or by the program when a runtime error occurs. When an exception is thrown from within a try block or a function called by one, the following occurs:

If an exception is thrown while no try blocks are executing, an error message is shown and the current thread exits.

The One True Brace (OTB) style may optionally be used with the try statement. For example:

try {
    ...
} catch e {
    ...
}

Related

Catch, Throw, Finally, Blocks, OnError

Examples

#1: The basic concept of try/catch/throw.

try  ; Attempts to execute code.
{
    HelloWorld
    MakeToast
}
catch e  ; Handles the first error/exception raised by the block above.
{
    MsgBox "An exception was thrown!`nSpecifically: " e
    Exit
}

HelloWorld()  ; Always succeeds.
{
    MsgBox "Hello, world!"
}

MakeToast()  ; Always fails.
{
    ; Jump immediately to the try block's error handler:
    throw A_ThisFunc " is not implemented, sorry"
}

#2: Handling basic failures of built-in functions.

try
{
    ; The following tries to back up certain types of files:
    FileCopy A_MyDocuments "\*.txt", "D:\Backup\Text documents"
    FileCopy A_MyDocuments "\*.doc", "D:\Backup\Text documents"
    FileCopy A_MyDocuments "\*.jpg", "D:\Backup\Photos"
}
catch
{
    MsgBox("There was a problem while backing the files up!",, 16)
    ExitApp
}

#3: Dealing with COM errors.

try
{
    obj := ComObjCreate("ScriptControl")
    obj.ExecuteStatement('MsgBox "This is embedded VBScript"')
    obj.InvalidMethod() ; This line produces a runtime error.
}
catch e
{
    ; For more detail about the object that e contains, see Exception.
    MsgBox("Exception thrown!`n`nwhat: " e.what "`nfile: " e.file 
        . "`nline: " e.line "`nmessage: " e.message "`nextra: " e.extra,, 16) 
}

#4: Nesting try-catch statements

try Example1 ; Any single statement can be on the same line with a Try statement.
catch e
    MsgBox "Example1() threw " e

Example1()
{
    try Example2
    catch e
    {
        if (e = 1)
            throw e ; Rethrow the exception so that the caller can catch it.
        else
            MsgBox "Example2() threw " e
    }
}

Example2()
{
    throw Random(1, 2)
}