syntax checking underway; question about catching exceptions

Fredrik Lundh fredrik at pythonware.com
Wed Dec 1 19:42:55 EST 1999


Preston Landers <prestonlanders at my-deja.com> wrote:
> If I catch the exception like so:
> 
> try:
>   compile(file, "", "exec")
> except:
>   exception, msg, tb = sys.exc_info()
>   # look at traceback here
> 
> then I effectively lose where in the source file the exception
> occured.  If I examine the tb with the traceback module, I get
> something like this:
> 
>   File "./syntax_checker.py", line 36, in examine_files
>     compile(file, "", "exec")
>
> So I can do post-processing, check other files, and so on, which is
> nice, but I am not able to determine automatically where the problem is
> in the source file.  So, it's effectively useless.

oh, you're close.  the exception instance (msg
in your case) contains the information you're
looking for.  consider this little example:

    import sys, traceback

    try:
        compile("""\
    while 1:
        prnt 'foo'
    """, "", "exec")
    except SyntaxError:
        ev = sys.exc_info()[1]
        for k, v in vars(ev).items():
            print k, "=", repr(v)

which prints:

    filename = None
    lineno = 2
    args = ('invalid syntax', (None, 2, 14, "    prnt 'foo'\012"))
    offset = 14
    text = "    prnt 'foo'\012"
    msg = 'invalid syntax'

also see:
http://www.python.org/doc/current/lib/module-exceptions.html

hope this helps!

</F>





More information about the Python-list mailing list