简体   繁体   English

当外部硬件连接失败时,我应该抛出什么 Python 异常?

[英]What Python exception should I throw when an external hardware connect fails?

I am writing some Python code that uses a library to communicate with an external piece of hardware over USB.我正在编写一些 Python 代码,该代码使用库通过 USB 与外部硬件进行通信。 When the hardware library is unable to connect to the device, it returns False - otherwise it returns True.当硬件库无法连接到设备时,它返回 False - 否则返回 True。

I would like to examine this return and use it to trigger an exception - to be more Pythonic.我想检查这个返回并用它来触发一个异常——更 Pythonic。 What would be the most appropriate exception type to throw?什么是最适合抛出的异常类型?

An IOError .一个IOError From the docs :文档

Raised when an I/O operation (such as a print statement, the built-in open() function or a method of a file object) fails for an I/O-related reason, eg, “file not found” or “disk full”.当 I/O 操作(例如 print 语句、内置 open() function 或文件对象的方法)由于 I/O 相关原因失败时引发,例如“找不到文件”或“磁盘”满的”。

You may want to wrap this in your own exception like:您可能希望将其包装在您自己的异常中,例如:

 class ExternalDeviceNotFound(IOError): pass

and raise that instead.而是提出来。 This gives the calling code more options on how to handle the error.这为调用代码提供了更多关于如何处理错误的选项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM