Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: try...except with wildcard for exception names?

I want to except only exceptions thrown by mutagen. However, there's a LOT of possible exceptions there. Is there some way I can wildcard (via regexp/etc) the exceptions handled by except? The alternative is just fugly...

mutagen.apev2.APEBadItemError
mutagen.apev2.APENoHeaderError
mutagen.apev2.KeyError
mutagen.apev2.ValueError
mutagen.easyid3.EasyID3KeyError
mutagen.easyid3.KeyError
mutagen.easyid3.ValueError
mutagen.flac.FLACNoHeaderError
mutagen.flac.FLACVorbisError
mutagen.flac.TypeError
mutagen.id3.EnvironmentError
mutagen.id3.EOFError
mutagen.id3.ID3BadCompressedData
mutagen.id3.ID3BadUnsynchData

and so on :P

like image 807
BrianFreud Avatar asked Aug 24 '26 19:08

BrianFreud


2 Answers

There's a less fugly way of going it, although it's still a slight pain, each of those modules implements an "error" that all of the relevant errors extend from.

# Please note, the exception class truly is lower cased as indicated
mutagen.id3.error
mutagen.flac.error
mutagen.apev2.error

# mutagen.easyid3 errors extend the mutagen.id3.error class
like image 73
Bryan Avatar answered Aug 27 '26 07:08

Bryan


This is pretty ugly too, but something like it might be a viable option in a case where you need to intercept a large, very heterogenous set of exceptions. At least it sequesters the long list of exceptions elsewhere.

>>> errors = {NameError:'a', ValueError:'b'}
>>> try:
...     cornucopia
... except Exception as e:
...     e_type = type(e)
...     if e_type in errors:
...         print errors[e_type]
...     else:
...         raise
... 
a

Obviously this is to be avoided if possible; Bryan Moyles's solution is probably preferable in your particular case. Still, thought I'd mention it.

like image 31
senderle Avatar answered Aug 27 '26 07:08

senderle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!