简体   繁体   中英

Which Python exception should I throw?

I'm writing some code to manipulate the Windows clipboard. The first thing I do is to try and open the clipboard with OpenClipboard() function from the Windows API:

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? I'm thinking WindowsError would be the right one, but not sure. 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. 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. From the docs:

exception WindowsError
Raised when a Windows-specific error occurs or when the error number does not correspond to an errno value. The winerror and strerror values are created from the return values of the GetLastError() and FormatMessage() functions from the Windows Platform API. The errno value maps the winerror value to corresponding errno.h values. ...

Raise the windows error and give it some extra infomation, for example

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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