[Q] raise exception with fake filename and linenumber
Gabriel Genellina
gagsl-py2 at yahoo.com.ar
Wed Apr 7 23:52:04 EDT 2010
En Wed, 07 Apr 2010 17:23:22 -0300, kwatch <kwatch at gmail.com> escribió:
> Is it possible to raise exception with custom traceback to specify
> file and line?
> I'm creating a certain parser.
> I want to report syntax error with the same format as other exception.
> -------------------------
> 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')
> -------------------------
>
> 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
> -------------------------
The built-in SyntaxError exception does what you want. Constructor
parameters are undocumented, but they're as follows:
raise SyntaxError("A descriptive error message", (filename, linenum,
colnum, source_line))
colnum is used to place the ^ symbol (10 in this fake example). Output:
Traceback (most recent call last):
File "1.py", line 9, in <module>
foo()
File "1.py", line 7, in foo
raise SyntaxError("A descriptive error message", (filename, linenum,
colnum, "this is line 123 in example.file"))
File "example.file", line 123
this is line 123 in example.file
^
SyntaxError: A descriptive error message
--
Gabriel Genellina
More information about the Python-list
mailing list