Throwステートメントによってスローされる実行時エラーや値に対して、1 つ以上のステートメントをガードします。
Try Statement
Try
{
Statements
}
The Try statement is usually followed by a block (one or more statements enclosed in braces). 実行する文が1つだけの場合は、Tryと同じ行か次の行に記述し、中括弧は省略できる。Tryがエラーをキャッチしたときだけ実行するコードを指定するには、1つ以上のCatchステートメントを使用します。
Catchや Finallyを使わずにTryを使うと、空のブロックでcatch Errorを実行するのと同じことになる。
実行時エラーが発生した場合、Throw文またはプログラムによって値が投げられる。TryブロックまたはTryブロックによって呼び出された関数の内部から値がスローされると、以下のことが起こる:
最後のCatchは、オプションで次のように続けることができます。 Else。例外がスローされることなく(ReturnやBreakなどで制御が他に移ることなく)Try文が完了すると、Else文が実行される。Else文でスローされた例外は、関連するTry文では処理されませんが、それを囲んでいるTry文によって処理される場合があります。Finallyも存在できるが、Elseの後に置かなければならず、常に最後に実行される。
One True Brace(OTB)スタイルは、オプションでTryステートメントと一緒に使用することができます。事例:
try {
...
} catch Error as err {
...
} else {
...
} finally {
...
}
Throw、Catch、Else、Finally、ブロック、OnError
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 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)
}