How do you use try except for library specific errors?

337 Views Asked by At

I am initializing a gamepad in my program, but if the gamepad isn't connected it will return the error:

pygame.error: Invalid joystick device number

My current code is this:

try:
    init_controller()
except pygame.error:
    use_keyboard = True

How would I format the except clause to except only this pygame error and not all pygame errors?

1

There are 1 best solutions below

0
On BEST ANSWER

Direct answer to your question: Since the exceptions are all the same type, then your options are limited to simply checking the exception message and then re-raise the exception if it's not a match. Or since you're only wrapping that function with try/except, it's safe to assume it's a joystick error and not something else. Buuuuut.....

The real answer to your question: You can check to see how many joysticks are present using pygame.joystick.get_count(). If it's 0, don't call the function.