You Are Here:

Community: Developer Discussion Boards

#1 Old Problem in Debugging (Handling Unexpected Errors) - 2008-08-20, 19:40

Join Date: Jul 2008
Posts: 25
Location: Tokyo, Japan
Hiisi
Offline
Registered User
Do you have any ideas to handle unexpected errors raised by functions which are called by users? Here is a simple example.

Code:
import sys
import e32
import appuifw

def raise_nameerror():
    """Raise NameError"""
    # foo = u'bar'
    foo

def main():
    """Main thread."""
    script_lock = e32.Ao_lock()
    appuifw.app.title = u'RaiseErrorTest'
    appuifw.app.body = appuifw.Text()
    appuifw.app.menu = [(u'Raise NameError', raise_nameerror),
                        (u'Exit', script_lock.signal)]
    appuifw.app.exit_key_handler = script_lock.signal
    script_lock.wait()

if __name__ == '__main__':
    try:
        main()
    except:
        appuifw.note(unicode(str(sys.exc_info()[0])), 'error')
I intend to catch exceptions with the last line, but as a result, I can't. (this script just keeps running) The only thing I can get is a traceback displayed in Python Script Shell AFTER stopping this script.

Meanwhile, if the functions containing error are called by script itself (not by users), error handling works fine.

Code:
import sys
import e32
import appuifw

def raise_nameerror():
    """Raise NameError"""
    # foo = u'bar'
    foo

def main():
    """Main thread."""
    raise_nameerror()

if __name__ == '__main__':
    try:
        main()
    except:
        appuifw.note(unicode(str(sys.exc_info()[0])), 'error')
If I can expect a function to raise exceptions, I can add "try and except" statement to such function in advance. (e.g. handling file may raise IOError etc.) But at the debugging stage, I can not expect which function may raise exceptions because of a lot of coding errors

I've referred to the article below, but this doesn't help me. So, if you have any good ideas to debug scripts quickly and efficiently, please let me know.

Python debugging techniques [Forum Nokia Wiki]
Reply With Quote

#2 Old Re: Problem in Debugging (Handling Unexpected Errors) - 2008-08-20, 22:03

Join Date: May 2004
Posts: 524
Location: Tampere, Finland
jethro.fn's Avatar
jethro.fn
Offline
Forum Nokia Champion
Exceptions from callbacks are not propagated to the "main thread" (in quotes because no real threading is going on in the background, only Symbian active objects).

You can wrap each callback in a function that collects the exception in a global list and signals the lock you're waiting. You can then handle exceptions collected in the list sequentially when the lock is signalled.

Here's the concept in code. It's crude and I have not tested it myself.

Code:
import traceback

# Exceptions from callbacks are collected here.
exceptions = []

# Decorator for callback functions
def collect_exception(func):
  # Using Python (>v2.2) nested scopes.
  def callit(*args, **kwds):
    global script_lock
    try:
      return func(*args, **kwds)
    except:
      excstr = "\n".join(traceback.format_exception(*sys.exc_info()))
      exceptions.append(excstr)  # Store exception string in a list.
      script_lock.signal()       # Notify main function about exception.
      raise                      # Re-raise exception, just in case.
  return callit

...

def main():
  global exceptions, script_lock

  script_lock = e32.Ao_lock()

  ...

  appuifw.app.menu = [(u'Raise NameError',
                       collect_exception(raise_nameerror)),
                      (u'Exit', 
                       script_lock.signal)]

  ...

  script_lock.wait()

  # Report exceptions. Could be more than one, in theory.
  for excstr in exceptions:
    appuifw.note(unicode(excstr), 'error')
  exceptions = []  # All exceptions accounted for, clear list.
EDIT: Whoops, there's no push() method on Lists. Changed to append().
Last edited by jethro.fn : 2008-08-21 at 07:37. Reason: Syntax error
Reply With Quote

#3 Old Re: Problem in Debugging (Handling Unexpected Errors) - 2008-08-21, 09:18

Join Date: Feb 2005
Posts: 1,353
Location: Belgium (Europe)
cyke64's Avatar
cyke64
Offline
Super Contributor
Quote:
Originally Posted by Hiisi View Post
Do you have any ideas to handle unexpected errors raised by functions which are called by users? Here is a simple example.

Code:
import sys
import e32
import appuifw

def raise_nameerror():
    """Raise NameError"""
    # foo = u'bar'
    foo

def main():
    """Main thread."""
    script_lock = e32.Ao_lock()
    appuifw.app.title = u'RaiseErrorTest'
    appuifw.app.body = appuifw.Text()
    appuifw.app.menu = [(u'Raise NameError', raise_nameerror),
                        (u'Exit', script_lock.signal)]
    appuifw.app.exit_key_handler = script_lock.signal
    script_lock.wait()

if __name__ == '__main__':
    try:
        main()
    except:
        appuifw.note(unicode(str(sys.exc_info()[0])), 'error')
I intend to catch exceptions with the last line, but as a result, I can't. (this script just keeps running) The only thing I can get is a traceback displayed in Python Script Shell AFTER stopping this script.

Meanwhile, if the functions containing error are called by script itself (not by users), error handling works fine.

Code:
import sys
import e32
import appuifw

def raise_nameerror():
    """Raise NameError"""
    # foo = u'bar'
    foo

def main():
    """Main thread."""
    raise_nameerror()

if __name__ == '__main__':
    try:
        main()
    except:
        appuifw.note(unicode(str(sys.exc_info()[0])), 'error')
If I can expect a function to raise exceptions, I can add "try and except" statement to such function in advance. (e.g. handling file may raise IOError etc.) But at the debugging stage, I can not expect which function may raise exceptions because of a lot of coding errors

I've referred to the article below, but this doesn't help me. So, if you have any good ideas to debug scripts quickly and efficiently, please let me know.

Python debugging techniques [Forum Nokia Wiki]
Hello ,

Try this little module HERE and follow this method
I hope you have success with it :-)

BR
Cyke64


pys60 1.4.5,1.9.7,pygame,PyS60 CE on E90 , N810 with Python 2.5.2 and ... last PyS60 1.9.7 with touch ui on 5800 !

pys60 extension modules on http://cyke64.googlepages.com/
Reply With Quote

#4 Old Re: Problem in Debugging (Handling Unexpected Errors) - 2008-08-21, 16:34

Join Date: Jul 2008
Posts: 25
Location: Tokyo, Japan
Hiisi
Offline
Registered User
Thank you for your quick replies.

I've integrated your two approaches into my sample script. (in order to show you a whole script)

Code:
import sys
import e32
import appuifw
import linecache

# Dubugging Level (0: Release, 1: Show Traceback, 2: Trace All)
debuglevel = 1

# Exceptions from callbacks are stored here.
exceptions = []

class Trace:
    """Class for tracing script
    
    This class is developed by cyke64.
    Lisenced under GNU GPL.
    """
    def __init__(self, runfile, f_all=u'E:\\Python\\traceit.txt',
                 f_main=u'E:\\Python\\traceitmain.txt'):
        self.out_all=open(f_all, 'w')
        self.out_main=open(f_main, 'w')
        self.runfile = runfile
      
    def go(self):
        sys.settrace(self.traceit)
    
    def stop(self):    
        sys.settrace(None)
        self.out_all.close()
        self.out_main.close()

    def traceit(self, frame, event, arg):
        lineno = frame.f_lineno
        name = frame.f_globals['__name__']
        if (frame.f_globals).has_key('__file__'):
            file_trace=frame.f_globals['__file__']
            line = linecache.getline(file_trace, lineno)
        else:
            file_trace = self.runfile
            line = linecache.getline(file_trace, lineno)
            self.out_main.write('%s*%s*\n*%s*\n' \
              % (event, lineno, line.rstrip()))
            self.out_all.write('%s*%s*of %s(%s)\n*%s*\n' \
              %(event, lineno, name, file_trace, line.rstrip()))
            e32.ao_sleep(0)
        return self.traceit

def call_callback(func):
    """Catch exeption
    
    This function is developed by jethro.fn.
    """
    def call_func(*args, **kwds):
        import traceback
        global exceptions
        global script_lock
        try:
            return func(*args, **kwds)
        except:
            # Collect Exceptions
            exception = ''.join(traceback.format_exception(*sys.exc_info()))
            exceptions.append(exception)
            
            # Signal lock in main thread (immediate termination)
            if debuglevel == 2: script_lock.signal()
    return call_func

def raise_nameerror():
    """Raise NameError"""
    # foo = u'bar'
    foo

def main():
    """Main thread"""
    global script_lock
    global exceptions
    
    # main UI
    script_lock = e32.Ao_lock()
    appuifw.app.title = u'RaiseErrorTest'
    appuifw.app.body = appuifw.Text()
    appuifw.app.menu = [(u'Raise NameError',
                           call_callback(raise_nameerror)),
                        (u'Exit', script_lock.signal)]
    appuifw.app.exit_key_handler = script_lock.signal
    script_lock.wait()
    
    # Handling exception
    if debuglevel and exceptions:
        show_traceback(exceptions)
        exceptions = []

def show_traceback(exceptions):
    """Show traceback"""
    appuifw.app.title = u'Traceback'
    traceback = '%d error(s) occurred.\n\n' % len(exceptions)
    for exception in  exceptions:
        traceback += '%s\n' % exception
    body = appuifw.Text(unicode(traceback))
    body.set_pos(0)
    appuifw.app.body = body
    appuifw.app.menu = [(u'Exit', script_lock.signal)]
    script_lock.wait()

if __name__ == '__main__':
    try:
        if debuglevel == 2:
            trace = Trace('E:\\Python\\RaiseErrorTest.py')
            trace.go()
            main()
            trace.stop()
        else:
            main()
    except:
        raise
It works lovely and surely helps me develop my applications.

Thank you again for your advices! Maybe I have to learn more and more about Python
Reply With Quote

#5 Old Re: Problem in Debugging (Handling Unexpected Errors) - 2008-08-21, 16:45

Join Date: May 2004
Posts: 524
Location: Tampere, Finland
jethro.fn's Avatar
jethro.fn
Offline
Forum Nokia Champion
Quote:
Originally Posted by Hiisi View Post
I've integrated your two approaches into my sample script. (in order to show you a whole script)

...

It works lovely and surely helps me develop my applications.
Wow. Seems pretty thorough. You wont miss a single exception with that thing...
Reply With Quote

#6 Old Re: Problem in Debugging (Handling Unexpected Errors) - 2008-08-22, 11:22

Join Date: Feb 2005
Posts: 1,353
Location: Belgium (Europe)
cyke64's Avatar
cyke64
Offline
Super Contributor
Quote:
Originally Posted by jethro.fn View Post
Wow. Seems pretty thorough. You wont miss a single exception with that thing...
YES !
Now we have a complete debugging tool because of Hiisi
You have a great blog on PyS60
Could you announce your most useful free applications(PyTask Server,PyBSLog and WAPlib) on DiBo ?
You could also add them to wiki application
I have added both debugging method + your very useful mixed method to the python debugging technics wiki page !

Happy debugging
Cyke64


pys60 1.4.5,1.9.7,pygame,PyS60 CE on E90 , N810 with Python 2.5.2 and ... last PyS60 1.9.7 with touch ui on 5800 !

pys60 extension modules on http://cyke64.googlepages.com/
Last edited by cyke64 : 2008-08-22 at 11:53. Reason: add three debugging methods to wiki !
Reply With Quote

#7 Old Re: Problem in Debugging (Handling Unexpected Errors) - 2008-08-23, 22:46

Join Date: Jul 2008
Posts: 25
Location: Tokyo, Japan
Hiisi
Offline
Registered User
Quote:
Originally Posted by cyke64 View Post
You have a great blog on PyS60
Could you announce your most useful free applications(PyTask Server,PyBSLog and WAPlib) on DiBo ?
You could also add them to wiki application
I've prepared a new simple Web page for distributing my free software: PyTaskServer, PyReboot, PyTwitterS60, and waplib module. (As for PyBSLog, I'm now preparing a document for it and can't announce it officially.) I'm new to Python language, so codes may be primitive. But at least, I'm trying to follow PEP 8.

I don't know how to announce my applications on this discussion board. (I'm also new to this community.) Could you tell me how to do that?

Thank you for your encouragement, cyke64
Reply With Quote

#8 Old Re: Problem in Debugging (Handling Unexpected Errors) - 2008-08-24, 06:05

Join Date: Feb 2008
Posts: 2,543
Location: Bhavnagar, Gujarat, India
Send a message via Yahoo to gaba88 Send a message via Skype™ to gaba88
gaba88's Avatar
gaba88
Online
Forum Nokia Champion
Quote:
Originally Posted by Hiisi View Post

I don't know how to announce my applications on this discussion board. (I'm also new to this community.) Could you tell me how to do that?
Hi Hiisi
first of all congrats for your so nice applications.
and its very easy to announce something in the discussion boards. Just start a new thread with the title of your new application and thats all.

Enjoy Pythoning
Gaba88


Gargi Das- http://gargidas.blogsot.com

Forum Nokia Python Wiki


Learn Python at http://mobapps.org/PyS60
Reply With Quote

#9 Old Re: Problem in Debugging (Handling Unexpected Errors) - 2008-08-24, 14:48

Join Date: Feb 2005
Posts: 1,353
Location: Belgium (Europe)
cyke64's Avatar
cyke64
Offline
Super Contributor
Quote:
Originally Posted by gaba88 View Post
Hi Hiisi
first of all congrats for your so nice applications.
and its very easy to announce something in the discussion boards. Just start a new thread with the title of your new application and thats all.

Enjoy Pythoning
Gaba88
As Gaba88 said to you just add in the the announce something like this (don't forget to add [announce] header !)

Code:
[announce] PyTwitterS60 0.0.2 : simplest Twitter client on PyS60
You could also add these applications in the new application page of PyS60 wiki

Happy pythoning
Cyke64


pys60 1.4.5,1.9.7,pygame,PyS60 CE on E90 , N810 with Python 2.5.2 and ... last PyS60 1.9.7 with touch ui on 5800 !

pys60 extension modules on http://cyke64.googlepages.com/
Reply With Quote

#10 Old Re: Problem in Debugging (Handling Unexpected Errors) - 2008-08-24, 16:13

Join Date: Jul 2008
Posts: 25
Location: Tokyo, Japan
Hiisi
Offline
Registered User
Thank you, gaba88 and cyke64.
I will try it later
Reply With Quote

#11 Old Re: Problem in Debugging (Handling Unexpected Errors) - 2008-08-24, 16:16

Join Date: Feb 2008
Posts: 2,543
Location: Bhavnagar, Gujarat, India
Send a message via Yahoo to gaba88 Send a message via Skype™ to gaba88
gaba88's Avatar
gaba88
Online
Forum Nokia Champion
Quote:
Originally Posted by Hiisi View Post
Thank you, gaba88 and cyke64.
I will try it later
hi hiisi
we all will be waiting for your application

Enjoy Pythoning
Gaba88


Gargi Das- http://gargidas.blogsot.com

Forum Nokia Python Wiki


Learn Python at http://mobapps.org/PyS60
Reply With Quote
Reply « Previous Thread | Next Thread »
Display Modes
Thread Tools Search this Thread
Search this Thread:

Advanced Search
Rate This Thread
Rate This Thread:

Posting Rules

You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Forum Jump
Similar Threads
Thread Thread Starter Forum Replies Last Post
A problem with debugging Helloworldbasic on the mobilephone lovemydoog Carbide.c++ IDE and plug-ins 23 2008-07-16 09:31
debugging multi language sis problem smui Carbide.c++ IDE and plug-ins 4 2008-05-31 00:06
problem related to multi media file handling deepakk General Symbian C++ 3 2008-05-20 13:00
Carbide.ui v3.2 - problem with N95 theme (call handling screens) liran2232 Themes/Carbide.ui 7 2008-05-13 19:45
e32std errors huge problem harish13_ks General Symbian C++ 1 2007-01-05 14:10

Rate This

 
Bookmark this page: DeliciousDiggFacebookGoogleYahooStumbleUponRedditDiigoTechnocratiTwitter  Share this page Share this page Print this Page Print this page Invite a friend Invite a friend
京ICP备05048969号    Email Newsletters Press Terms & Conditions Privacy Policy Sitemap Contact Us © 2009 Nokia