Dzhao
Dzhao

Reputation: 693

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!

Upvotes: 7

Views: 4618

Answers (1)

Goodies
Goodies

Reputation: 4681

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")

Upvotes: 3

Related Questions