简体   繁体   English

我应该抛出哪个Python异常?

[英]Which Python exception should I throw?

I'm writing some code to manipulate the Windows clipboard. 我正在编写一些代码来操纵Windows剪贴板。 The first thing I do is to try and open the clipboard with OpenClipboard() function from the Windows API: 我要做的第一件事是尝试使用Windows API中的OpenClipboard()函数打开剪贴板:

if OpenClipboard(None): 
    # Access the clipboard here     
else:
    # Handle failure

This function can fail. 此功能可能会失败。 So if it does, I would like to raise an exception. 因此,如果有的话,我想提出一个例外。 My question is, which of the standard Python exceptions should I raise? 我的问题是,我应该提出哪些标准的Python异常? I'm thinking WindowsError would be the right one, but not sure. 我认为WindowsError是正确的选择,但不确定。 Could someone please give me a suggestion? 有人可以给我一个建议吗?

It is better to avoid raising standard exceptions directly. 最好避免直接引发标准异常。 Create your own exception class, inherit it from the most appropriate one ( WindowsError is ok) and raise it. 创建自己的异常类,从最合适的异常类继承( WindowsError可以)并引发它。 This way you'll avoid confusion between your own errors and system errors. 这样,您将避免自己的错误和系统错误之间的混淆。

WindowsError seems a reasonable choice, and it will record extra error information for you. WindowsError似乎是一个不错的选择,它将为您记录更多的错误信息。 From the docs: 从文档:

exception WindowsError WindowsError异常
Raised when a Windows-specific error occurs or when the error number does not correspond to an errno value. 在发生Windows特定错误或错误号与errno值不对应时引发。 The winerror and strerror values are created from the return values of the GetLastError() and FormatMessage() functions from the Windows Platform API. Winerror和strerror值是根据Windows Platform API的GetLastError()和FormatMessage()函数的返回值创建的。 The errno value maps the winerror value to corresponding errno.h values. errno值将winerror值映射到相应的errno.h值。 ... ...

Raise the windows error and give it some extra infomation, for example 引发Windows错误并为其提供一些额外信息,例如

raise WindowsError("Clipboard can't be opened")

Then when its being debugged they can tell what your windows error means rather than just a random windowserror over nothing. 然后,在对其进行调试时,它们可以告诉您Windows错误的含义,而不仅仅是一个无所不能的随机Windows错误。

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

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