472,368 Members | 2,644 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

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

error handling

I want to handle errors for a program i'm building in a specific way,
but I don't want to use try/except/finally because it requires forming
new blocks of code. I want to be able things like this:

a = [2, 423, "brownie", 234.34]
try: a[890]
except IndexError: # I don't use 'finally' here because I specifically
want to check for an IndexError
sys.exit("That number is way too big!")

But sometimes you can have too many of these statements in your
program, and it starts to get tangled and nasty looking. Is there a way
I can modify sys.error so that when the interpreter comes accross an
IndexError it prints "That number is way too big!" before it exits?

Aug 10 '06 #1
7 2048
Chris wrote:
But sometimes you can have too many of these statements in your
program, and it starts to get tangled and nasty looking. Is there a way
I can modify sys.error so that when the interpreter comes accross an
IndexError it prints "That number is way too big!" before it exits?
Hi,

Try placing the try/except block around the main function of your program:

if __name__ == '__main__':
try:
main()
except IndexError:
sys.exit("That number is way too big!")

-Farshid
Aug 10 '06 #2
Chris wrote:
I want to handle errors for a program i'm building in a specific way,
but I don't want to use try/except/finally because it requires forming
new blocks of code. I want to be able things like this:

a = [2, 423, "brownie", 234.34]
try: a[890]
except IndexError: # I don't use 'finally' here because I specifically
want to check for an IndexError
sys.exit("That number is way too big!")

But sometimes you can have too many of these statements in your
program, and it starts to get tangled and nasty looking. Is there a way
I can modify sys.error so that when the interpreter comes accross an
IndexError it prints "That number is way too big!" before it exits?
You don't want to do what because why? Huh?

I'm sorry man, I don't want to be harsh, but use try..except blocks.

If your code is getting "tangled and nasty looking" you probably need
to break it up into small[er] functions, or redesign it somehow.

Peace,
~Simon

(Also, there's no such thing as sys.error, do you mean
sys.excepthook()?)

Aug 10 '06 #3
I want to do this because there are several spots in my program where
an error might occur that I want to handle the same way, but I don't
want to rewrite the try..except block again. Is that clearer?

And I meant sys.stderr... sorry 'bout that

Simon Forman wrote:
Chris wrote:
I want to handle errors for a program i'm building in a specific way,
but I don't want to use try/except/finally because it requires forming
new blocks of code. I want to be able things like this:

a = [2, 423, "brownie", 234.34]
try: a[890]
except IndexError: # I don't use 'finally' here because I specifically
want to check for an IndexError
sys.exit("That number is way too big!")

But sometimes you can have too many of these statements in your
program, and it starts to get tangled and nasty looking. Is there a way
I can modify sys.error so that when the interpreter comes accross an
IndexError it prints "That number is way too big!" before it exits?

You don't want to do what because why? Huh?

I'm sorry man, I don't want to be harsh, but use try..except blocks.

If your code is getting "tangled and nasty looking" you probably need
to break it up into small[er] functions, or redesign it somehow.

Peace,
~Simon

(Also, there's no such thing as sys.error, do you mean
sys.excepthook()?)
Aug 11 '06 #4

Chris wrote:
I want to handle errors for a program i'm building in a specific way,
but I don't want to use try/except/finally because it requires forming
new blocks of code. I want to be able things like this:

a = [2, 423, "brownie", 234.34]
try: a[890]
except IndexError: # I don't use 'finally' here because I specifically
want to check for an IndexError
sys.exit("That number is way too big!")

But sometimes you can have too many of these statements in your
program, and it starts to get tangled and nasty looking. Is there a way
I can modify sys.error so that when the interpreter comes accross an
IndexError it prints "That number is way too big!" before it exits?
Call me crazy, but I don't think convoluted mucking about to produce
"That number is way too big!" -- especially when it could be negative
(way too small) -- is better than doing nothing (no try/except at all)
and getting "list index out of range":

#>>a = [1,42, 666]
#>>a[890]
Traceback (most recent call last):
File "<stdin>", line 1, in ?
IndexError: list index out of range
#>>>

Although the manual says "In particular, sys.exit("some error message")
is a quick way to exit a program when an error occurs." this is
scarcely to be recommended. You should at the very least produce a
stack trace so that you can see *where* the error occurred.

<rant>
If you are interacting with a user, you need to give feedback for
*expected* problems like invalid input as close to the point of error
as possible -- online: validate the input before attempting to use it;
batch -- validate it and give feedback which pinpoints the problem (and
it may be required to identify all problems, not just bail out on
seeing the first puff of flak). If it is for your own use: do yourself
a favour and treat yourself like a customer should be treated. You
should have traps for *unexpected* exceptions that likewise pinpoint
what was happening when the exception occurred.

Consider dumping salient info to a file before pulling the ripcord --
that way you don't have to rely on users reporting what they thought
they saw before hitting the power button. Time passing has not meant
progress; user memory capacity has not increased and the usual
cycle-power response time is worse; rebooting a PC takes way longer
than rebooting a green-screen terminal :-)
</rant>

HTH,
John

Aug 11 '06 #5
On Thu, 10 Aug 2006 16:59:56 -0700, Farshid Lashkari wrote:
Chris wrote:
>But sometimes you can have too many of these statements in your
program, and it starts to get tangled and nasty looking. Is there a way
I can modify sys.error so that when the interpreter comes accross an
IndexError it prints "That number is way too big!" before it exits?

Hi,

Try placing the try/except block around the main function of your program:

if __name__ == '__main__':
try:
main()
except IndexError:
sys.exit("That number is way too big!")

That's broken.

Imagine that somewhere in main() the following is called:

D = {"a": "apple", "b": "bicycle", "c": "cat"}
print D["aardvark"]

Your code now prints "That number is way too big!". That's not good.

try...except blocks should, as a general rule, cover only the smallest
amount of code that they need to.

One possible solution is to use a custom class:

# untested
class MyList(list):
def __getitem__(self, i):
if i >= len(self):
raise IndexError("That index is too big!")
super(list, self).__getitem__(i)

Another is a helper function:

def safe_getindex(somelist, i):
if i >= len(somelist):
raise IndexError("That index is too big!")
return somelist[i]
You can of course re-write them to use a try...except block instead of
testing the index.
--
Steven D'Aprano

Aug 11 '06 #6
In article <11*********************@74g2000cwt.googlegroups.c om>,
Chris <ch*********@gmail.comwrote:
>I want to do this because there are several spots in my program where
an error might occur that I want to handle the same way, but I don't
want to rewrite the try..except block again. Is that clearer?
Aug 11 '06 #7
Steven D'Aprano wrote:
That's broken.

Imagine that somewhere in main() the following is called:

D = {"a": "apple", "b": "bicycle", "c": "cat"}
print D["aardvark"]

Your code now prints "That number is way too big!". That's not good.

try...except blocks should, as a general rule, cover only the smallest
amount of code that they need to.
Hi Steven,

Point taken and I think your solution better addresses the root of the
problem. However, the OP said he wanted to print out that error message
whenever the interpreter came across any IndexError. So I gave him what
he wanted. I guess he needs to be more careful what he wishes for ;)

-Farshid
Aug 11 '06 #8

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

Similar topics

2
by: WSeeger | last post by:
When creating a new class, is it encouraged to always include error handling routines within your LET and GET procedures? It's seems that most text books never seem to include much about error...
12
by: Christian Christmann | last post by:
Hi, assert and error handling can be used for similar purposes. When should one use assert instead of try/catch and in which cases the error handling is preferable? I've read somewhere that...
6
by: Squirrel | last post by:
I have a command button on a subform to delete a record. The only statement in the subroutine is: DoCmd.RunCommand acCmdDeleteRecord The subform's recordsource is "select * from tblVisit order...
13
by: Thelma Lubkin | last post by:
I use code extensively; I probably overuse it. But I've been using error trapping very sparingly, and now I've been trapped by that. A form that works for me on the system I'm using, apparently...
21
by: Anthony England | last post by:
Everyone knows that global variables get re-set in an mdb when an un-handled error is encountered, but it seems that this also happens when the variable is defined as private at form-level. So...
3
by: Stefan Johansson | last post by:
Hi all I'am moving from Visual Foxpro and have a question regarding "best practice" error handling in vb .net. In VFP I have always used a "central" error handling object in order to have a...
4
by: Al Williams | last post by:
Hi, I have error handling in place throughout my application. I also start the application wrapped in error handling code to catch any unexpected exceptions (i.e. exceptions that occur where I...
10
by: Anthony England | last post by:
(sorry for the likely repost, but it is still not showing on my news server and after that much typing, I don't want to lose it) I am considering general error handling routines and have...
0
by: Lysander | last post by:
Thought I would give something back with a few articles. This article is a bit of code to add error handling. When I have time, I want to write articles on multilingual databases, and Access...
9
by: MrDeej | last post by:
Hello guys! We have an SQL server which sometimes makes timeouts and connection errors. And we have an function witch writes and updates data in 2 tables on this server. When the SQL server error...
0
by: Naresh1 | last post by:
What is WebLogic Admin Training? WebLogic Admin Training is a specialized program designed to equip individuals with the skills and knowledge required to effectively administer and manage Oracle...
0
by: antdb | last post by:
Ⅰ. Advantage of AntDB: hyper-convergence + streaming processing engine In the overall architecture, a new "hyper-convergence" concept was proposed, which integrated multiple engines and...
0
by: Arjunsri | last post by:
I have a Redshift database that I need to use as an import data source. I have configured the DSN connection using the server, port, database, and credentials and received a successful connection...
0
hi
by: WisdomUfot | last post by:
It's an interesting question you've got about how Gmail hides the HTTP referrer when a link in an email is clicked. While I don't have the specific technical details, Gmail likely implements measures...
1
by: Matthew3360 | last post by:
Hi, I have been trying to connect to a local host using php curl. But I am finding it hard to do this. I am doing the curl get request from my web server and have made sure to enable curl. I get a...
0
by: Carina712 | last post by:
Setting background colors for Excel documents can help to improve the visual appeal of the document and make it easier to read and understand. Background colors can be used to highlight important...
0
by: Rahul1995seven | last post by:
Introduction: In the realm of programming languages, Python has emerged as a powerhouse. With its simplicity, versatility, and robustness, Python has gained popularity among beginners and experts...
2
by: Ricardo de Mila | last post by:
Dear people, good afternoon... I have a form in msAccess with lots of controls and a specific routine must be triggered if the mouse_down event happens in any control. Than I need to discover what...
1
by: Johno34 | last post by:
I have this click event on my form. It speaks to a Datasheet Subform Private Sub Command260_Click() Dim r As DAO.Recordset Set r = Form_frmABCD.Form.RecordsetClone r.MoveFirst Do If...

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.