[Q] raise exception with fake filename and linenumber

kwatch kwatch at gmail.com
Wed Apr 7 22:23:22 CEST 2010


Hi all,

Is it possible to raise exception with custom traceback to specify
file and line?

Situation
=========

I'm creating a certain parser.
I want to report syntax error with the same format as other exception.

Example
=======

parser.py:
-------------------------
1: def parse(filename):
2:     if something_is_wrong():
3:         linenum = 123
4:         raise Exception("syntax error on %s, line %s" % (filename,
linenum))
5:
6: parse('example.file')
-------------------------

current result:
-------------------------
Traceback (most recent call last):
  File "/tmp/parser.py", line 6, in <module>
    parse('example.file')
  File "/tmp/parser.py", line 4, in parse
    raise Exception("syntax error on %s, line %s" % (filename,
linenum))
Exception: syntax error on example.file, line 123
-------------------------

my hope is:
-------------------------
Traceback (most recent call last):
  File "/tmp/parser.py", line 6, in <module>
    parse('example.file')
  File "/tmp/parser.py", line 4, in parse
    raise Exception("syntax error on %s, line %s" % (filename,
linenum))
  File "/tmp/example.file", line 123
    foreach item in items   # wrong syntax line
Exception: syntax error
-------------------------

I guess I must create dummy traceback data, but I don't know how to do
it.
Could you give me an advice?

Thank you.

--
regards,
makoto kuwata



More information about the Python-list mailing list