473,387 Members | 1,465 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

Resume after exception

Hi there,

Is it possible to have an 'except' case which passes control back to the
point after the exception occurred?

e.g.

# a function to open the file
# raises FileLockedException is file contains 'locked' information
def open_file(file_name):
f = file(file_name, 'r')
{read first line for file lock info}
if first_line == "FILE LOCKED":
raise FileLockedException(lock_user, lock_timestamp)
{read remainder of file}
return True

# elsewhere in a user interface module
def open_command():
try:
open_file("foo.bar")
except FileLockException, X:
ans = tkMessageBox.askyesno(title="File Locked", message="File
locked by '" + X.user + "' on " + X.time_stamp + "\nContinue
anyway?")
if ans == tkMessageBox.YES:
# return control to the remainder of the open_file function.
How?
else:
return False

Any ideas?

Cheers,
Richard
Jul 19 '05 #1
4 10435
On Tue, 14 Jun 2005 10:09:30 +0100,
"Richard Lewis" <ri**********@fastmail.co.uk> wrote:
Hi there,
Is it possible to have an 'except' case which passes control back to the
point after the exception occurred?


Not that I can think of.

[ example of "interrupting" a file-reading function in order to ask the
user if they really want to read a locked file ]

I would rewrite that this way (untested, and without error checking):

def open_file(file_name, read_if_locked=False):
f = file(file_name)
[read first line]
if first_line == "FILE LOCKED" and read_if_locked == FALSE:
return False
[read the rest]
return True

def open_command():
if open_file("foo.bar") == False:
[ask the user what to do]
if ans == tkMessageBox.YES:
open_file("foo.bar", True )

Regards,
Dan

--
Dan Sommers
<http://www.tombstonezero.net/dan/>
Jul 19 '05 #2
Why does the first function return True? Shouldn't it return the file
content? That's at least what the function name implies.
You call the second function open_command() which returns a boolean.
Feels wrong.

Where you have written "How?" I suggest that you replace that by:
return open_file("foo.bar", 1)

and change open_file() to look something like this:
def open_file(file_name, ignore_lock=False):
f = file(file_name, 'r')
{read first line for file lock info}
if first_line == "FILE LOCKED" and not ignore_lock:
raise FileLockedException(lock_user, lock_timestamp)
{read remainder of file}
return True

Jul 19 '05 #3
Richard Lewis wrote:
Is it possible to have an 'except' case which passes control back to the
point after the exception occurred?


Basically no, although I could imagine some gross hack with the frame
info and some bytecode hacks that effect a "goto". Basically the stack
frame gets unwound to the point where the exception is caught. If you
need recoverability, write your open_file function to be resumable in
some way.

Note that you could easily (perhaps) implement this as a callable
object, with the required state stored internally, and make the result
almost indistinguishable from what you are asking for:

I could imagine an API allowing something like this:

open_file = RecoverableOpenFileThingy()

while not open_file.completed:
try:
open_file("foo.bar")
except FileLockException, ex:
# blah blah
if ans != tkMessageBox.YES:
open_file.completed = True

But since your open_file() doesn't seem likely to be doing anything
particularly complicated, I really doubt you need the complexity of a
special class here. Just stick the relevant code inside a loop, much
like that above, and break out of the loop when things succeed.

(What internal state do you think the open_file procedure would have to
maintain, which you would be trying to resume? If you are just going to
go back to the beginning of it and try again, you don't need anything
like what you asked for, just a regular loop.)
Jul 19 '05 #4
Richard Lewis schreef:
Is it possible to have an 'except' case which passes control back to the
point after the exception occurred?


No, not in Python. The concept has however been discussed, under the
name "resumable exceptions".

http://www.google.com/search?num=100...e%3Apython.org

An excellent article about the concept was written by Kent Pitman:

"Condition Handling in the Lisp Language Family"
http://www.nhplace.com/kent/Papers/C...ling-2001.html

Common Lisp is a language that does have the feature. Your code would
be written in Lisp like below. When the function notices the file is
locked, it will raise an exception. Now imagine there are two ways to
solve the problem: 1) read the file anyway, despite the lock; 2) clear
the lock and read the file. Or reading the file could be cancelled.
These three possible ways to continue the execution are set up by
"restart-case". (So this is actually a generalization of your request,
in that instead of "just continueing", you can direct the way of
continuing)

(defun read-unlocked-file (file-name)
(with-open-file (f file-name)

(when (string= (read-line f) "FILE LOCKED")
(let ((user "lock-user")
(timestamp 123))
(restart-case (error 'file-locked :name file-name
:user user :timestamp timestamp)
(continue () :report "Continue reading the locked file.")
(clear-lock () :report "Clear the lock and continue reading"
(warn "clearing lock..."))
(abort () :report "Abort reading the file."
(return-from read-unlocked-file)))))

(warn "reading remainder of file...")
t))

When reading a locked file, you end up with this message:

CL-USER(31): (read-unlocked-file "file.txt")
Error: File file.txt was locked by lock-user at time 123.
[condition type: FILE-LOCKED]

Restart actions (select using :continue):
0: Continue reading the locked file.
1: Clear the lock and continue reading
2: Abort reading the file.
3: Return to Top Level (an "abort" restart).
4: Abort entirely from this process.

Note the three first "restart actions" are the ones we just defined
inside "read-unlocked-file". Let's continue execution by clearing the
lock (restart number 1):

[1] CL-USER(32): :continue 1
Warning: clearing lock...
Warning: reading remainder of file...
T

If Python had restarts, in your example you would set up code that,
depending on whether the user clicked "abort" or "continue" in the
dialog, automatically invokes the corresponding restart to either
continue or abort the calculation.

Restarts are pretty cool. Maybe Stackless Python could support it
fairly easily, restarts basically being named continuations?
- Willem

Jul 19 '05 #5

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

Similar topics

2
by: Darta | last post by:
OK- I volunteer to be shot if this question is stupid... BUT, is there a way to, when you catch an exception in the catch{} handler, resume to the same line of code that generated an error while...
5
by: Rob R. Ainscough | last post by:
Coming from VB6 to VB.NET, it appears if I opt to use the Try Catch approach I don't have any way to RESUME from within my catch statement? What I often do is resolve the problem in my catch...
5
by: itsupport1 | last post by:
Hi, I am importing some records from one table to another table, and due to Constraints in the destination table, it Throws an Exception and Skip the Whole Rest of records. So I did implement...
15
by: Neo | last post by:
Hello All, Although, I have read all the advantages of using Try Catch Block instead of "On error goto", I am still confused what is alternative for classic "Resume" statement. "Resume" was one...
7
by: fniles | last post by:
In VB 6.0 in the error trapping, we can do "resume next" to continue on the next code. How can we do that in .NET with "Try", "Catch","End Try" ? Thanks
7
by: Rob R. Ainscough | last post by:
In VB6 I can use Resume Next to execute the line of coding following the line that cause an exception. There doesn't appear to be anything similiar when using Try...Catch -- so how can one resume...
11
by: Maxwell2006 | last post by:
Hi, I know that this is not a good practice, but I wonder do we have "on error resume next" in C#? Thanks,
8
by: Adil Akram | last post by:
There are situations where you want to retry/rerun the same code again (if user wants) for unlimited times for a particular exception thrown. For example in situations like there's no CD in the...
19
by: kimiraikkonen | last post by:
Hi, I want to find out if there's difference between "On Error Resume Next" error handler and leaving "catch" block empty in a try-catch-end try block to ignore exceptions which i don't approve of...
3
by: sriharikabattula | last post by:
hi, i am uploading .doc,.docX,rtf files during registration level and that path can be saved in database(i am using database MYSQL).when user want to see his resume he/she can login and retrive...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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...
0
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,...
0
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...

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.