Try

Guards one or more statements against runtime errors and values thrown by the Throw statement.

Try Statement
Try
{
    Statements
}

備考

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 one or more Catch statements.

CatchFinallyを使わずにTryを使うと、空のブロックでcatch Errorを実行するのと同じことになる。

実行時エラーが発生した場合、Throw文またはプログラムによって値が投げられる。TryブロックまたはTryブロックによって呼び出された関数の内部から値がスローされると、以下のことが起こる:

最後のCatchは、オプションで次のように続けることができます。 Else. 例外がスローされることなく(ReturnBreakなどで制御が他に移ることなく)Try文が完了すると、Else文が実行される。Else文でスローされた例外は、関連するTry文では処理されません。Finallyも存在できるが、Elseの後に置かなければならず、常に最後に実行される。

One True Brace (OTB) スタイルは、オプションでTryステートメントと一緒に使用することができます。事例:

try {
    ...
} catch Error as err {
    ...
} else {
    ...
} finally {
    ...
}

Throw, Catch, Else, Finally, Blocks, OnError

Try-CatchThrowの基本概念を示す。

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

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

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

組込み関数の基本的なエラー処理を示す。

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!",, "IconX"
    ExitApp 1
}
else
{
    MsgBox "Backup successful."
    ExitApp 0
}

COMエラーを処理するTry-Catchの使用法を示す。以下で使用するCOMオブジェクトの詳細については、ScriptControlの使用法(Microsoft Docs)を参照してください。

try
{
    obj := ComObject("ScriptControl")
    obj.ExecuteStatement('MsgBox "This is embedded VBScript"')  ; This line produces an Error.
    obj.InvalidMethod()  ; This line would produce a MethodError.
}
catch MemberError  ; Covers MethodError and PropertyError.
{
    MsgBox "We tried to invoke a member that doesn't exist."
}
catch as e
{
    ; For more detail about the object that e contains, see Error Object.
    MsgBox("Exception thrown!`n`nwhat:" e.what "`nfile:" e.file
        . "`nline:" e.line "`nmessage:" e.message "`nextra:" e.extra,, 16)
}

Try-Catchステートメントの入れ子を示す。

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

Example1()
{
    try Example2
    catch Number as e
    {
        if (e = 1)
            throw ; Rethrow the caught value to our caller.
        else
            MsgBox "Example2() threw " e
    }
}

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