错误处理

From Apache OpenOffice Wiki
Jump to: navigation, search
The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.
doc OOo
Book.png


正确处理出现的错误情况是最耗时的编程任务之一。Apache OpenOffice Basic 提供了一系列用于简化错误处理的工具。

On Error 指令

On Error 指令是任何错误处理的关键所在:

Sub Test
  On Error Goto ErrorHandler
  ' ... undertake task during which an error may occur
  Exit Sub
  ErrorHandler: 
    ' ... individual code for error handling
End Sub

On Error Goto ErrorHandler 行定义了当发生错误时 Apache OpenOffice Basic 采取何种操作。Goto ErrorHandler 确保 Apache OpenOffice Basic 退出当前程序行,然后执行 ErrorHandler: 代码。

Resume 命令

在执行错误处理程序中的代码后,Resume Next 命令从程序中发生错误的位置的下一行开始继续执行程序:

ErrorHandler:
  ' ... individual code for error handling
  Resume Next

使用 Resume Proceed 命令可以指定一个跳转点,以便在错误处理后继续执行程序:

ErrorHandler:
  ' ... individual code for error handling
  Resume Proceed
 
Proceed:
  ' ... the program continues here after the error

要在发生错误时继续执行程序而不生成错误消息,请使用以下格式:

Sub Test
  On Error Resume Next
  ' ... perform task during which an error may occur
End Sub

应谨慎使用 On Error Resume Next 命令,因为其影响是全局性的。

有关错误信息的查询

在错误处理过程中,如果有错误说明并知道发生错误的位置和原因,会非常有用:

  • Err 变量包含已发生的错误数目。
  • Error$ 变量包含错误说明。
  • Erl 变量包含发生错误的行的编号。

调用

 MsgBox "Error " & Err & ": " & Error$ & " (line : " & Erl & ")"

说明如何在消息窗口中显示错误信息。

Documentation note.png VBA 在一个名为 Err 的统计对象中总结错误消息;而 Apache OpenOffice Basic 提供的是 Err, Error$Erl 变量。

在程序遇到 ResumeOn Error 命令之前,状态信息一直有效,遇到这些命令后将重置该信息。

Documentation note.png 在 VBA 中,Err 对象的 Err.Clear 方法将在发生错误后重置错误状态。在 Apache OpenOffice Basic 中,将使用 On ErrorResume 命令完成此操作。

有关结构化错误处理的提示

定义命令 On Error 和返回命令 Resume 都是 Goto 结构的变体。

如果要清晰地定义代码结构,以防止在使用此结构时产生错误,在使用跳转命令时应对其进行监视。

在使用 On Error Resume Next 命令时应格外小心,因为它会关闭所有打开的错误消息。

最好的解决办法是在一个程序中仅使用一种错误处理方法,将错误处理与实际程序代码分隔开来,且错误发生后不跳转回原始代码。

以下代码是一个错误处理过程示例:

Sub Example
  ' Define error handler at the start of the function 
  On Error Goto ErrorHandler   
    ' ... Here is the actual program code
  On Error Goto 0           ' Deactivate error handling
    ' End of regular program implementation
  Exit Sub

 ' Start point of error handling
 ErrorHandler:                
   ' Check whether error was expected
    If Err = ExpectedErrorNo Then   
      ' ... Process error
    Else
      ' ... Warning of unexpected error
    End If
 On Error Goto 0            ' Deactivate error handling 
End Sub

此过程的开头处定义了一个错误处理程序,然后是实际的程序代码。在程序代码结尾处,通过 On Error Goto 0 调用停用了错误处理,并通过 Exit Sub 命令(不要与 End Sub 相混淆)结束了过程实现。

该示例首先检查错误编号是否与预期的编号(存储在虚拟的 ExpectedErrorNo 常量中)相对应,然后对该错误进行相应处理。如果发生其他错误,系统将会输出一个警告。检查错误编号至关重要,因为这样可检测到非预期的错误。

代码结尾处的 On Error Goto 0 调用会重置错误的状态信息(Err 系统变量中的错误代码),以便清楚地识别以后发生的错误。

Content on this page is licensed under the Public Documentation License (PDL).


Personal tools