Try
提供: AutoHotkey Wiki
実行制御 | GUI表示 | 演算・変数 | メモリ・DLL操作 | 文字列操作 |
キーボード | マウス | シェル | ウィンドウ | ウィンドウグループ
ステータスバー | コントロール | サウンド | ファイル | INIファイル |
レジストリ | 環境変数 | AutoHotkey | その他 | 設定関係 | オブジェクト
Try [v1.1.04+][編集]
AHKL 実行時エラーとThrowコマンドによって送られるエラー(例外)を使用して1つ以上の「コマンド/式」を保護する。
Try Statement
Try { Statements }
Remarks[編集]
Tryコマンドは通常、ブロック続き - {}
で囲まれた1つ以上の「コマンド/式」。
単一文を実行する場合はTryと同じ行または次の行に配置することができ{}
を省略することができる。
Tryがエラーをキャッチした場合に実行されるコードを指定するにはCatchコマンドを使用する。
Throwコマンドが使用中または、実行時エラーがTryブロックの実行中に検出された場合、直ちに実行中ブロックの外にジャンプする。Catch文がある場合、それが実行される。 Tryブロックが実行されていない時に例外がスローされた場合、エラーメッセージが表示され現在のスレッドが終了する。
複数のTryコマンドが実行されている場合、実行中の最新の物が優先される。
必要に応じて以下のような配置ができる。
Try { ... } Catch e { ... }
Related[編集]
Example(s)[編集]
; Example #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" }
; Example #2: Using 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 }
; Example #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 Catch.
MsgBox, 16,, % "Exception thrown!`n`nwhat: " e.what "`nfile: " e.file . "`nline: " e.line "`nmessage: " e.message "`nextra: " e.extra }
; Example #4: Nesting Try-Catch statements.
Try Example1(); Any single statement can be on the same line with a Try command.
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 }