简体   繁体   中英

How do I check for a certain type of OSError in a try except block?

I have some code that potentially could raise an OSError based on the user's input. More specifically, it could raise OSError: [WinError123] . The problem I'm facing is that my try except block checks for OSError which is way too broad of an exception.

I've looked at this question and this question however, it's unclear to me how errno works. I've also looked at the errno documentation but it is unclear to me how it relates to the specific errors within OSError .

How do I catch a specific OSError namely, WinError 123 ?

Also if you could explain to me what libraries you utilized / how you did it / the thought process of your solution would be wonderful!

Can you not do something like:

try:
    my_function()
except OSError as e:
    if e.args[0] != 123:
        raise
    print("Deal with the 123 error here")

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