473,575 Members | 3,366 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Exception feature creep! (was: re-entering in the normal flow after an exception is raised)

In a recent post, Michele Simionato asked about resumable (or
re-entrant) exceptions, the basic idea being that when raised and
uncaught, these exceptions would only propagate backwards through a
limited number of frames before being implicitly ignored. Alex
Martelli pointed out that resumable exceptions are difficult to
implement, and that the need for them isn't pressing because it's
pretty easy to write a program with explicit error handling that works
just fine, citing Bjarne Stroustrup's thoughts on the same topic for
C++.
This is probably quite right.

Nonetheless, I tried to write some demo code that implemented
resumable exceptions, but ran face-first into a brick wall: I
couldn't find any way to manipulate the call stack (to execute code in
a frame other than the current one)

What if exceptions were given more control?

Proposal:

1. Call a __raise__ method in the exception when raised
2. Call an __uncaught__ method in every frame for which the exception
is not handled by an except clause. __uncaught__ would decide
whether or not to continue to propagate the exception to the next
frame. If __uncaught__ decides to abort the exception, then the
calling statement is aborted/ignored--- the implicit equivalent of:

try:
do_something()
except:
pass
Anyway, this is just idle speculation. I don't really see a need for
it, but it's interesting to ponder.
Here are some hypothetical uses:
1. An exception that propagates only n frames:

class QuietException( Exception):
def __init__(self, n):
Exception.__ini t__(self)
self.n = n

def __raise__(self) :
self.counter = self.n

def __uncaught__(se lf):
if self.counter > 0:
self.counter -= 1
return True
else:
return False

2. An exception that keeps a traceback as it goes:

class TracingExceptio n(Exception):

def __raise__(self) :
self.traceback = []

def __uncaught__(se lf):
self.traceback. append(sys._get frame(1))

....

try:
foo()
except TracingExceptio n, e:
# isn't this more elegant than sys.last_traceb ack?
import traceback
traceback.print _tb(e.traceback )
3. An exception that resumes execution if some global FAULT_TOLERANT
is true:

class FaultTolerantEx ception(Excepti on):
def __uncaught__(se lf):
return not FAULT_TOLERANT
Jul 18 '05 #1
8 1670
Lonnie Princehouse ha scritto:
In a recent post, Michele Simionato asked about resumable (or
re-entrant) exceptions, the basic idea being that when raised and
uncaught, these exceptions would only propagate backwards through a
limited number of frames before being implicitly ignored.


I don't understand: why resumable exceptions should be ignored after
they propagate for a limited number of frames?

the only idea of resumable exceptions I have is that they allow you to ,
well, resume excution from the point they were raised.
Jul 18 '05 #2
gabriele renzi wrote:
I don't understand: why resumable exceptions should be ignored after
they propagate for a limited number of frames?

the only idea of resumable exceptions I have is that they allow you to
,
well, resume excution from the point they were raised.


Right. The idea is that you can catch the exception and resume it, in
which case execution continues from the point that the resumable
exception was _raised_. The exception, when caught, can still be
reraised (and another catcher resuming it will still cause it to resume
from the original point it was raised). If the exception is not caught,
then it acts as a normal exception and halts the program with a stack
trace.

--
__ Erik Max Francis && ma*@alcyone.com && http://www.alcyone.com/max/
/ \ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis
\__/ The color is red / Under my shoe
-- Neneh Cherry
Jul 18 '05 #3
fi************* *@gmail.com (Lonnie Princehouse) wrote in message news:<4b******* *************** ****@posting.go ogle.com>...
In a recent post, Michele Simionato asked about resumable (or
re-entrant) exceptions, the basic idea being that when raised and
uncaught, these exceptions would only propagate backwards through a
limited number of frames before being implicitly ignored.


Well, actually that is NOT what I asked. Erik Max Francis got my point:

"""
The idea is that you can catch the exception and resume it, in
which case execution continues from the point that the resumable
exception was _raised_. The exception, when caught, can still be
reraised (and another catcher resuming it will still cause it to resume
from the original point it was raised). If the exception is not caught,
then it acts as a normal exception and halts the program with a stack
trace.
"""

I have no idea about how difficult would be to implement resumable exceptions
in Python; also I am not sure about their cost vs. benefit. For sure, in
2.5 years of Python programming this is first time I have got an use case
for resumable exceptions; still it is a contrived case. So, I am not in
dire need of resumable exceptions.
Nevertheless, it is possible that if we had resumable exceptions we
could use them as a control flow structure in non-exceptional situations.
One could speculate about the idea ...

Michele Simionato
Jul 18 '05 #4
Michele Simionato wrote:
I have no idea about how difficult would be to implement resumable
exceptions
in Python; also I am not sure about their cost vs. benefit. For sure,
in
2.5 years of Python programming this is first time I have got an use
case
for resumable exceptions; still it is a contrived case. So, I am not
in
dire need of resumable exceptions.
Nevertheless, it is possible that if we had resumable exceptions we
could use them as a control flow structure in non-exceptional
situations.
One could speculate about the idea ...


Resumable exceptions are for when you want to flag cases that may be
exceptional, but that some users of the library may not care about. A
good example would be a forgiving parser, where resumable exceptions
would be thrown whenever a technical violation, but one that can be
recovered from, occurs. This is actually a lot more common than you
think; Web browsers and server-side email processing systems are good
examples, where you may want to know about technical violations of
standards and RFCs, but still need to do something meaningful anyway.
In those cases, someone using the library can not bother catching those
resumable exceptions, in which case they'll act as normal exceptions, or
they can catch them and do something meaningful with them, or they can
simply blanket catch them and immediately resume, something like:

...
except (FirstResumable Exception, SecondResumable Exception), e:
e.resume()

Obviously, there are other ways to accomplish this, but they have to use
some mechanism other than exceptions.

--
__ Erik Max Francis && ma*@alcyone.com && http://www.alcyone.com/max/
/ \ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis
\__/ I will always remember / This moment
-- Sade
Jul 18 '05 #5
mi************* **@gmail.com (Michele Simionato) writes:
Nevertheless, it is possible that if we had resumable exceptions we
could use them as a control flow structure in non-exceptional situations.
One could speculate about the idea ...


Sure. You could raise a resumable exception whose handler runs some
code before resuming after the exception. The handling code could do
some stuff that raises its own resumable exception. Now you have two
resumable exceptions pending, and it would be cool if you could resume
the first one before resuming the second. In fact what you'd really
like is a "resumption " object created by raising the exception, that
you can pass control to at any time, sort of like yielding from a
generator. Maybe you're getting deja vu now, since this is basically
what Stackless Python continuations were. They give you a simple way
to implement coroutines and just about anything else you could want.
Jul 18 '05 #6
On 1 Oct 2004 12:52:38 -0700, Lonnie Princehouse wrote:
In a recent post, Michele Simionato asked about resumable (or
re-entrant) exceptions, the basic idea being that when raised and
uncaught, these exceptions would only propagate backwards through a
limited number of frames before being implicitly ignored. Alex
What a strange idea.
Nonetheless, I tried to write some demo code that implemented
resumable exceptions, but ran face-first into a brick wall: I
couldn't find any way to manipulate the call stack (to execute code in
a frame other than the current one)


The mistake you're making is to conflate Python's exceptions with the
resumable exceptions you're trying to implement. Python exceptions
are more like Common Lisp's catch/throw mechanism (sort of a
dynamically scoped "goto") than they are like the condition system.
You can use Python's exception mechanism for the primitive control
transfer, and build something on top of that (but since you can't
write syntax in Python it's going to be butt-ugly). That's what Shai
Berger was trying to do.

Keep a list of (exception-type, function) pairs. Where you want a
try/except, write a try/finally instead, with the "try" part pushing
"except" handlers on the front of this list, and the "finally" part
taking them back off (to emulate dynamic binding...don't use threads).
Instead of using raise, look up the exception type in this list and
call the associated function, so it runs above the failure point in
the call stack (but note that it has to transfer control somewhere
else if you don't want to return). For restarts, do a similar thing,
mapping restart names to ("randomly" named) exception subclasses (as
catch tags); where you want a restart, write try/except using that
subclass name, push it on the restarts list, and to invoke it look up
the name and use raise on the tag. Or something.

--
Malum est consilium quod mutari non potest -- Publilius Syrus

(setq reply-to
(concatenate 'string "Paul Foley " "<mycroft" '(#\@) "actrix.gen.nz> "))
Jul 18 '05 #7
Michele Simionato ha scritto:

Nevertheless, it is possible that if we had resumable exceptions we
could use them as a control flow structure in non-exceptional situations.
One could speculate about the idea ...


I have the feeling I don't have an use for resumable exceptions mainly
because I was never exposed to the them.
Kind of a blub paradox.

I wonder if StacklessPython can handle this.
Resumable Exceptions are really easy to do if you can grab the current
continuation, but I seem to remember conts were banned from the
stackless world.
Jul 18 '05 #8
mi************* **@gmail.com (Michele Simionato) wrote in message news:<4e******* *************** ****@posting.go ogle.com>...

Well, actually that is NOT what I asked. Erik Max Francis got my point:


Indeed! I seem to have completely misinterpreted your post!

At least it.. raised.. some interesting conjecture about exceptions.
I wonder if yield could be abused to simulate resumable exceptions
under certain situations?

class ResumableExcept ion(Exception): pass

def foo():
if something_has_g one_wrong():
yield ResumableExcept ion
print "Resumed!"
result = foo()
if result is ResumableExcept ion:
if recovery_is_pos sible():
foo()
else:
raise result

Far from ideal, but it is a way of suspending and then resuming
execution. It does have the unfortunate caveat that the caller needs
to be aware of what's coming, which sort of defeats the point of
exceptions. A kind of homage to the things people do in languages
that lack exception-handling mechanisms...
Jul 18 '05 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
1673
by: Michele Simionato | last post by:
I think I want "re-entrant exceptions" (not sure if this is the correct name). Consider the following example: class NotSeriousException(Exception): pass def do_this(): raise NotSeriousException()
0
354
by: Ola | last post by:
I just installed VS.Net but when I try to open any of the solution (.sln) files. I get a crash and dump with the following message "An unhandled exception has been caught by the VSW exception filter." I have sifted through numerous messages in the newsgroups with no luck on how to investigate or solve this problem. Any ideas, suggestions are...
5
1261
by: pbo.spam | last post by:
I have a little problem. I designed a webpage (VB.Net) with code behind "Page_Load". If the process works fine, the page is shown. If the process raises an exception, I catch it and modify a label inside the page (red color, ...) But, the page is not displayed. I only have a blank screen. No error page, no nothing.. just stops.
0
1163
by: lou_1 | last post by:
i get this error when i try to open one my CrystalReports files. A windows pops up and says "Microsoft Development Environment has encountered a problem and needs to close..." When i click on the "click here" link to see details about the error it says: "An unhandled exception has been caught by the VSW exception filter. AppName:...
5
2019
by: Alan Silver | last post by:
Hello, I have a page that is supposed to do some checking, and if OK, set a session variable before redirecting to another page. The following code is a simplified version, I have hard-coded the basket ID and removed a load of extra checking... public partial class GoToCheckout : Page { public void Page_Load(Object o, EventArgs e) { try...
5
6132
by: darrel | last post by:
I have a function that calls a class that writes a dataset that I've passed to it out as an excel spreadheet and returns it to the browser: my function try makeExcelFile(mydataset) catch response write the exceptions end try end function
4
4894
by: Totto | last post by:
Hi, I'm doing a server.transfer from a click event of a button, but an exception is raised with "Thread was being aborted" Anyone know why? Thanks Tor
1
2729
by: strakamichal | last post by:
Hi all, i need help with one exception. I know only .Message of this exception and i know which part of code throws it. .Message: "The operation was canceled." try { FileIOPermission perm = new FileIOPermission(FileIOPermissionAccess.Write, file_name); perm.Assert();
2
2791
by: strakamichal | last post by:
Hi all, i need help with one exception. I know only .Message of this exception and i know which part of code throws it. .Message: "The operation was canceled." try
0
7775
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
8120
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
8281
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7868
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
8143
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6515
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
0
5338
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3778
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
1107
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.