How do I catch ExpatError exception?

S

Shuaib

Hey!

I am getting this exception.

xml.parsers.expat.ExpatError

But I am not able to catch it with "except
xml.parsers.expat.ExpatError:" It says "NameError: global name 'xml' is
not defined".

I am also not able to catch it with "except ExpatError:" Gives
"NameError: global name 'xml' is not defined"

How do I catch it? (I am parsing an xml file)

Also, how do I get the line number where an exception was thrown?

Thanks.
 
M

Mark Winrock

Shuaib said:
Hey!

I am getting this exception.

xml.parsers.expat.ExpatError

But I am not able to catch it with "except
xml.parsers.expat.ExpatError:" It says "NameError: global name 'xml' is
not defined".

I am also not able to catch it with "except ExpatError:" Gives
"NameError: global name 'xml' is not defined"

How do I catch it? (I am parsing an xml file)

Have you imported xml.parsers.expat to get it properly scoped?
Also, how do I get the line number where an exception was thrown?
Try looking at the 'sys.exc_info' and the 'traceback' module
documentation. Also see Python Cookbook recipe Recipe 8.6. Getting More
Information from Tracebacks (Bryn Keller)
 
S

Steve Holden

Shuaib said:
Hey!

I am getting this exception.

xml.parsers.expat.ExpatError

But I am not able to catch it with "except
xml.parsers.expat.ExpatError:" It says "NameError: global name 'xml' is
not defined".

I am also not able to catch it with "except ExpatError:" Gives
"NameError: global name 'xml' is not defined"

How do I catch it? (I am parsing an xml file)
import xml.parsers.expat

That way the interpreter will be able to resolve the reference to the
exception.
Also, how do I get the line number where an exception was thrown?
#
# Exception traceback test
#
def r():
return 1/0

try:
print r()
except:
import sys
t, v, tb = sys.exc_info()

print "exception on line", tb.tb_lineno

regards
Steve
 
S

Shuaib

Steve said:
import xml.parsers.expat


Thanks, that worked.

def r():
return 1/0

try:
print r()
except:
import sys
t, v, tb = sys.exc_info()

print "exception on line", tb.tb_lineno

How do I get the helpful text that is thrown with the exception? Like
if the exception is " IOError: [Errno 2] No such file or directory:
'out.xml' "

How do I get the the text after IOError: ?

Thanks again.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,774
Messages
2,569,599
Members
45,163
Latest member
Sasha15427
Top