异常处理

From Apache OpenOffice Wiki
Jump to: navigation, search



与 UNO 不同,Basic 不支持异常。Basic 运行时系统捕获 UNO 抛出的所有异常,并将其转换为 Basic 错误。执行以下代码会导致 Basic 错误,该错误会中断代码执行过程,并显示一条错误消息:

 Sub Main
     Dim oLib
     oLib = BasicLibraries.getByName( "InvalidLibraryName" )
 End Sub

示例中使用的 BasicLibraries 对象包含正在运行的办公软件实例中的所有可用 Basic 程序库。BasicLibraries 中包含的 Basic 程序库可使用 com.sun.star.container.XNameAccess 进行访问。尝试获取一个不存在的库时触发了一个异常。 OpenOffice.org Basic 和对话框 - 高级程序库组织中更加详细地说明了 BasicLibraries 对象。


调用 getByName() 会导致出现以下错误框:

未处理的 UNO 异常


但是,Basic 运行时系统并不总是能够识别异常类型。有时,仅显示对象实现提供的异常消息。使用 On Error GoTo 命令,可以像处理任何 Basic 错误一样来处理转换成 Basic 错误的异常:

Exceptions transformed to Basic errors can be handled just like any Basic error using the On Error GoTo command:

 Sub Main
     On Error Goto ErrorHandler ' Enables error handling
     
     Dim oLib
     oLib = BasicLibraries.getByName( "InvalidLibraryName" )
     MsgBox "After the Error"
     Exit Sub
   
 ' Label
 ErrorHandler:
     MsgBox "Error code: " + Err + Chr$(13) + Error$
     Resume Next ' Continues execution at the command following the error command
 End Sub

When the exception occurs, the execution continues at the ErrorHandler label. In the error handler, some properties are used to get information about the error. The Err is the error code that is 1 for UNO exceptions. The Error$ contains the text of the error message. Executing the program results in the following output:

发生异常时,从 ErrorHandler 标签处继续执行。在错误处理程序中,使用某些属性来获取错误信息。Err 是错误代码,1 代表 UNO 异常。Error$ 包含错误消息的文字。执行程序会导致以下输出:

已处理的 UNO 异常


在上面的对话框之后,出现另一个消息框 “After the Error”,因为 Resume Next 使程序转到抛出异常的代码行的下一行。Exit Sub 命令是必需的,这样才可以再次执行错误处理程序代码。

错误处理后的 MsgBox
Content on this page is licensed under the Public Documentation License (PDL).
Personal tools
In other languages