Try [v1.1.04+]

Guards one or more statements 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 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 Try. For example:

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

Catch, Throw, Finally, Blocks, OnError()

Examples

Demonstrates the basic concept of Try-Catch and 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"
}

Demonstrates the use of Try-Catch instead of ErrorLevel.

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, 16,, There was a problem while backing the files up!
    ExitApp
}

Demonstrates the use of Try-Catch dealing with COM errors. For details about the COM object used below, see Using the ScriptControl (Microsoft Docs).

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, 16,, % "Exception thrown!`n`nwhat: " e.what "`nfile: " e.file
        . "`nline: " e.line "`nmessage: " e.message "`nextra: " e.extra
}

Demonstrates nesting Try-Catch statements.

try Example1() ; Any single statement can be on the same line with Try.
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()
{
    Random, o, 1, 2
    throw o
}