守护一个或多个语句(命令或表达式)以防备由 throw 命令抛出的运行时错误和异常.
Try Statement
Try
{
Statements
}
try 命令后常跟着 代码区块 - 括在大括号中的一个或多个语句 (命令或表达式). 如果仅需执行单个语句, 那么此语句可以和 try 放在同一行或在其下一行, 并且可以省略大括号. 要指定仅在 try 捕获到错误时执行的代码, 请使用 catch 命令.
throw 命令或程序在运行时遇到错误时会抛出异常.当 try 区块或由其调用的函数抛出异常时,将进行下列操作:
如果在 try 区块外执行时抛出异常,则显示错误信息并退出当前线程.
One True Brace (OTB) 风格 可以用在 try 命令中. 例如:
try {
...
} catch e {
...
}
; 示例 #1: try/catch/throw 的基本概念.
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"
}
; 示例 #2: 使用 try/catch 代替 ErrorLevel.
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
}
; 示例 #3: 处理 COM 错误.
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
}
; 示例 #4: 嵌套的 try-catch 语句.
try Example1() ; 单个语句可以和 Try 命令放在同一行.
catch e
MsgBox, Example1() threw %e%.
Example1()
{
try Example2()
catch e
{
if e = 1
throw e ; 重新抛出这个异常, 这样调用者可以捕获它.
else
MsgBox, Example2() threw %e%.
}
}
Example2()
{
Random, o, 1, 2
throw o
}