【发布时间】:2021-09-10 07:40:20
【问题描述】:
要重现该问题,请使用以下 shell 命令打开一个 calc 文件
me@konsoles$ soffice --calc --accept="socket,host=localhost,port=2002;urp;StarOffice.ServiceManager"
在不同的控制台运行python并输入以下命令
me@konsoles$ python
Python 3.7.5 (default, Feb 23 2021, 13:22:40)
[GCC 8.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import uno
>>> local_context = uno.getComponentContext()
>>> resolver = local_context.ServiceManager.createInstanceWithContext("com.sun.star.bridge.UnoUrlResolver", local_context)
>>> ctx = resolver.resolve("uno:socket,host=localhost,port=2002;urp;StarOffice.ComponentContext")
>>> smgr = ctx.ServiceManager
>>> desktop = smgr.createInstanceWithContext("com.sun.star.frame.Desktop", ctx)
>>> file_handle = desktop.getCurrentComponent()
>>> print("connected to", file_handle.getTitle())
connected to Untitled 1
因此您可以看到 file_handle 已连接到 uno 对象。
我只是想验证没有错误的工作表作为 getByName 方法的参数输入;如果您确实提供了错误的工作表名称,则会引发 NoSuchElementException
>>> test = file_handle.getSheets().getByName("kanoedel")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
__main__.NoSuchElementException
所以你会假设一个 try 除了 woudl 抓住它,但它没有定义,它抛出它但没有抓住它,嗯!?
>>> try:
... test = file_handle.getSheets().getByName("kanoedel")
... except NoSuchElementException:
... print("GD")
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
__main__.NoSuchElementException
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<stdin>", line 3, in <module>
NameError: name 'NoSuchElementException' is not defined
主要问题是,我如何捕获该异常?
【问题讨论】:
-
你能分享一下第一次创建 NoSuchElementException 的代码吗?
-
我认为您无法捕捉到该异常,它是在 C code 中提出的。
-
我已经仔细查看了这个概念的定义位置,但我无法找到模块,可能是 import uno 语句隐式导入它
-
有人可以告诉我如何模拟这个“不可捕获”异常吗?我完全迷路了
标签: python unit-testing exception