Is there a way to continue after an exception ?

Ryan Kelly ryan at rfk.id.au
Sat Feb 20 21:51:21 EST 2010


On Sun, 2010-02-21 at 13:17 +1100, Lie Ryan wrote:
> On 02/21/10 12:02, Stef Mientki wrote:
> > On 21-02-2010 01:21, Lie Ryan wrote:
> >>> On Sun, Feb 21, 2010 at 12:52 AM, Stef Mientki
> <stef.mientki at gmail.com> wrote:
> >>>
> >>>> hello,
> >>>>
> >>>> I would like my program to continue on the next line after an uncaught
> >>>> exception,
> >>>> is that possible ?
> >>>>
> >>>> thanks
> >>>> Stef Mientki
> >>>>
> >>>>
> >> That reminds me of VB's "On Error Resume Next"
> >>
> > I think that's what I'm after ...
>
> A much better approach is to use callbacks, the callbacks determines
> whether to raise an exception or continue execution:
> 
> def handler(e):
>     if datetime.datetime.now() >= datetime.datetime(2012, 12, 21):
>         raise Exception('The world has ended')
>     # else: ignore, it's fine
> 
> def add_ten_error_if_zero(args, handler):
>     if args == 0:
>         handler(args)
>     return args + 10
> 
> print add_ten_error_if_zero(0, handler)
> print add_ten_error_if_zero(10, handler)
> print add_ten_error_if_zero(0, lambda e: None) # always succeeds


Or if you don't like having to explicitly manage callbacks, you can try
the "withrestart" module:

    http://pypi.python.org/pypi/withrestart/

It tries to pinch some of the good ideas from Common Lisp's
error-handling system.

  from withrestart import *

  def add_ten_error_if_zero(n):
      #  This gives calling code the option to ignore
      #  the error, or raise a different one.
      with restarts(skip,raise_error):
          if n == 0:
              raise ValueError
      return n + 10

  # This will raise ValueError
  print add_ten_error_if_zero(0)

  # This will print 10
  with Handler(ValueError,"skip"):
      print add_ten_error_if_zero(0)

  # This will exit the python interpreter
  with Handler(ValueError,"raise_error",SystemExit):
      print add_ten_error_if_zero(0)



  Cheers,

      Ryan


-- 
Ryan Kelly
http://www.rfk.id.au  |  This message is digitally signed. Please visit
ryan at rfk.id.au        |  http://www.rfk.id.au/ramblings/gpg/ for details

-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 197 bytes
Desc: This is a digitally signed message part
URL: <http://mail.python.org/pipermail/python-list/attachments/20100221/2b2e29aa/attachment.sig>


More information about the Python-list mailing list