守护一个或多个语句(命令或表达式) 不受 throw 命令抛出的运行时错误和异常的影响.
Try Statement
Try
{
Statements
}
try 命令后常跟着代码区块 - 括在大括号中的一个或多个语句(命令或表达式). 如果仅需执行单个语句, 那么此语句可以和 try 放在同一行或在其下一行, 并且可以省略大括号. 要指定仅在 try 捕获到错误时执行的代码, 请使用 catch 命令.
throw 命令或程序在运行遇到错误时会抛出异常. 当 try 区块或由其调用的函数抛出异常时, 将进行下列操作:
如果在 try 区块外执行时抛出异常, 则显示错误信息并退出当前线程.
One True Brace(OTB) 风格可以用在 try 命令中. 例如:
try {
...
} catch e {
...
}
Catch, Throw, Finally, 区块, OnError()
try ; 尝试执行的代码.
{
HelloWorld()
MakeToast()
}
catch e ; 处理由上面区块产生的首个错误/异常.
{
MsgBox, An exception was thrown!`nSpecifically: %e%
Exit
}
HelloWorld() ; 总是成功.
{
MsgBox, Hello, world!
}
MakeToast() ; 总是失败.
{
; 立即跳到 try 区块的错误处理程序:
throw A_ThisFunc " is not implemented, sorry"
}
try
{
; 下列语句尝试备份某些指定类型的文件:
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
}
演示使用 try/catch 处理 COM 错误. 有关下面使用的 COM 对象的详情, 请参阅 Using the ScriptControl (Microsoft Docs).
try
{
obj := ComObjCreate("ScriptControl")
obj.ExecuteStatement("MsgBox ""This is embedded VBScript""")
obj.InvalidMethod() ; 此行会产生运行时错误.
}
catch e
{
; 关于 e 对象的更多细节, 请参阅 Exception().
MsgBox, 16,, % "Exception thrown!`n`nwhat: " e.what "`nfile: " e.file
. "`nline: " e.line "`nmessage: " e.message "`nextra: " e.extra
}