3

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()?

Grezzo
  • 2,220
  • 2
  • 22
  • 39

2 Answers2

2

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

m.wasowski
  • 6,329
  • 1
  • 23
  • 30
  • 1
    Could you give an example of the 2nd option if you don't know the exception name¿? – aDoN Dec 18 '15 at 10:15
  • That sounds like a good idea, but in practice, the docs for the lib I'm using doesn't even mention `ExpatError` (https://docs.python.org/3/library/xml.dom.minidom.html). Maybe I'm looking in the wrong place, can you direct me to the right place? – Grezzo Dec 18 '15 at 13:44
1

A good place to start are the 'Built-in Exceptions' of Python. With some study you can tell what operation can cause which exception. The documentation is also particularly useful as it provides practical examples.

Specifically in your case, you are performing file Input/Output operations (IO) and IO operations are handled generally as:

try:
    with open('path_to_file', 'permission') as f:
        #do something with the file
except IOError as e:
    print e
ciacicode
  • 708
  • 1
  • 5
  • 13