Guards one or more statements (commands or expressions) against runtime errors and exceptions thrown by the throw command.
Try Statement
Try
{
Statements
}
The try command is usually followed by a block - one or more statements (commands 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 command.
An exception can be thrown by the throw command 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 command. For example:
try { ... } catch e { ... }
Catch, Throw, Finally, Blocks, OnError()
Demonstrates 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" }
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 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 }