Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I know which exceptions to catch in Python

In Python, I've read that it's better (and easier) to catch execptions, rather than check first, so that's what I'm trying to do.

My script opens and parses an XMLs file using

xml.dom.minidom.parse(xml_file_path)

so I'm catching

xml.parsers.expat.ExpatError

but if the file doesn't exist, I get a FileNotFoundError exception, so I obviously need to catch that too.

I know that I shouldn't really be catching all exceptions, but how can I know what exceptions I should be catching for a function like parse()?

like image 441
Grezzo Avatar asked Jul 15 '26 14:07

Grezzo


1 Answers

You can consult documentation of library you use. And even better you can write a test where you trigger exception first. Then you will know exactly what exception you need to catch (and have another test to guard you in the future).

like image 64
m.wasowski Avatar answered Jul 18 '26 15:07

m.wasowski



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!