473,388 Members | 1,399 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,388 software developers and data experts.

Correct use of try,except and raise?

Is this correct use of exceptions? to raise an indexerror and add my
own string insetad of just letting it raise a IndexError by itself and
"blaming" it on list.pop?

class Stack(object):
def __init__(self, *items):
self.stack = list(items)

def push(self, item):
self.stack.append(item)

def pop(self):
try:
return self.stack.pop()
except:
raise IndexError, "pop from empty stack"

class Queue(object):
def __init__(self, *items):
self.queue = list(items)

def append(self, item):
self.queue.append(item)

def pop(self):
try:
return self.queue.pop(0)
except:
raise IndexError, "pop from empty queue"
Jul 12 '08 #1
9 5131
In article
<3b**********************************@p25g2000hsf. googlegroups.com>,
ssecorp <ci**********@gmail.comwrote:
Is this correct use of exceptions? to raise an indexerror and add my
own string insetad of just letting it raise a IndexError by itself and
"blaming" it on list.pop?

class Stack(object):
def __init__(self, *items):
self.stack = list(items)

def push(self, item):
self.stack.append(item)

def pop(self):
try:
return self.stack.pop()
except:
raise IndexError, "pop from empty stack"

class Queue(object):
def __init__(self, *items):
self.queue = list(items)

def append(self, item):
self.queue.append(item)

def pop(self):
try:
return self.queue.pop(0)
except:
raise IndexError, "pop from empty queue"
I think you would do better defining a new exception, PopError, or
something like that. Then you can write code which specifically catches
that and do something with it.

It's also not a good idea to catch all exceptions. Catch the most specific
thing you can. Consider something like:

try:
kew.pop(0)
except:
raise IndexError, "pop from empty kew"

When I run it, it prints, "IndexError: pop from empty kew". The problem
is, the *real* error is "NameError: name 'kew' is not defined". By
catching all exceptions, I've masked a programming error by turning the
NameError into an IndexError.
Jul 13 '08 #2
On Jul 13, 2:32*am, Roy Smith <r...@panix.comwrote:
In article
<3b78898b-6131-4137-9c1d-64deaf460...@p25g2000hsf.googlegroups.com>,

*ssecorp <circularf...@gmail.comwrote:
Is this correct use of exceptions? to raise an indexerror and add my
own string insetad of just letting it raise a IndexError by itself and
"blaming" it on list.pop?
class Stack(object):
* * def __init__(self, *items):
* * * * self.stack = list(items)
* * def push(self, item):
* * * * self.stack.append(item)
* * def pop(self):
* * * * try:
* * * * * * return self.stack.pop()
* * * * except:
* * * * * * raise IndexError, "pop from empty stack"
class Queue(object):
* * def __init__(self, *items):
* * * * self.queue = list(items)
* * def append(self, item):
* * * * self.queue.append(item)
* * def pop(self):
* * * * try:
* * * * * * return self.queue.pop(0)
* * * * except:
* * * * * * raise IndexError, "pop from empty queue"

I think you would do better defining a new exception, PopError, or
something like that. *Then you can write code which specifically catches
that and do something with it.

It's also not a good idea to catch all exceptions. *Catch the most specific
thing you can. *Consider something like:

try:
* * kew.pop(0)
except:
* *raise IndexError, "pop from empty kew"

When I run it, it prints, "IndexError: pop from empty kew". *The problem
is, the *real* error is "NameError: name 'kew' is not defined". *By
catching all exceptions, I've masked a programming error by turning the
NameError into an IndexError.


i dont get what you mean, if i dont do anything python will raise an
indexerror so it is an indexerror.
Jul 13 '08 #3
ssecorp <ci**********@gmail.comwrote:
i dont get what you mean, if i dont do anything python will raise an
indexerror so it is an indexerror.
You wrote:
* * def pop(self):
* * * * try:
* * * * * * return self.queue.pop(0)
* * * * except:
* * * * * * raise IndexError, "pop from empty queue"
You are assuming that the only possible exception that can be thrown by
"return self.queue.pop(0)" is IndexError. Maybe, maybe not. I gave you
one example of how something else could be thrown -- a typo in your code
leading to a NameError. Maybe even something more exotic like MemoryError?

The defensive thing to do is catch exactly the exception you expect to
happen. In this case, that means IndexError.
Jul 13 '08 #4
ssecorp <ci**********@gmail.comwrites:
Is this correct use of exceptions? to raise an indexerror and add my
own string insetad of just letting it raise a IndexError by itself
and "blaming" it on list.pop?

class Stack(object):
def __init__(self, *items):
self.stack = list(items)
If you are passing a sequence conceptually, then it's more Pythonic to
pass it as a sequence explicitly::

def __init__(self, items):
""" Call with e.g. Stack(["foo", "bar"]) """
self.stack = list(items)
def pop(self):
try:
return self.stack.pop()
except:
raise IndexError, "pop from empty stack"
Don't use this form of 'raise', it's deprecated. Instead, create the
exception instance with the arguments::

raise IndexError("pop from empty stack")

Don't use a bare 'except'; you will thereby catch *all* exceptions in
the 'try' block, masking errors you did not expect to handle, making
debugging unnecessarily difficult. Instead, always be explicit about
*which* exceptions you're handling here.

Don't catch the exception only to raise a new one; the context of the
original exception is lost. If all you want to do is have a different
message, modify the existing exception instance's args and re-raise
it.

try:
return self.stack.pop()
except IndexError, exc:
exc.args = ["pop from empty stack"]
raise

--
\ “Experience is that marvelous thing that enables you to |
`\ recognize a mistake when you make it again.” —Franklin P. Jones |
_o__) |
Ben Finney
Jul 13 '08 #5
Roy Smith <ro*@panix.comwrites:
ssecorp <ci**********@gmail.comwrote:
>i dont get what you mean, if i dont do anything python will raise an
indexerror so it is an indexerror.

You wrote:
* * def pop(self):
* * * * try:
* * * * * * return self.queue.pop(0)
* * * * except:
* * * * * * raise IndexError, "pop from empty queue"

You are assuming that the only possible exception that can be thrown by
"return self.queue.pop(0)" is IndexError. Maybe, maybe not. I gave you
one example of how something else could be thrown -- a typo in your code
leading to a NameError. Maybe even something more exotic like MemoryError?

The defensive thing to do is catch exactly the exception you expect to
happen. In this case, that means IndexError.
And you do that by

except IndexError:
raise TheErrorYouNowWantToRaise

And
except IndexError, e:

if you want access to the exception as well.
Jul 13 '08 #6
Bart Kastermans <ka******@bart-kastermanss-macbook.localwrites:
Roy Smith <ro*@panix.comwrites:
The defensive thing to do is catch exactly the exception you
expect to happen. In this case, that means IndexError.

And you do that by

except IndexError:
raise TheErrorYouNowWantToRaise
You only do that if you want to throw away important information, such
as the traceback associated with the original exception. Not very
friendly to debugging.
And
except IndexError, e:

if you want access to the exception as well.
Usually best if it can be achieved. Not least because the bare 'raise'
statement will re-raise the original exception, complete with all its
context.

--
\ “If we don't believe in freedom of expression for people we |
`\ despise, we don't believe in it at all.” —Noam Chomsky, |
_o__) 1992-11-25 |
Ben Finney
Jul 13 '08 #7
Ben Finney <bi****************@benfinney.id.auwrote:
If you are passing a sequence conceptually, then it's more Pythonic to
pass it as a sequence explicitly::

def __init__(self, items):
""" Call with e.g. Stack(["foo", "bar"]) """
self.stack = list(items)
I don't get this. You're forcing a copy to be made of the list. This
changes the semantics of the original class, because the operations no
longer change the original list. That may or may not be what you want.
It's a design decision, not a "doing it this way is more pythonic" kind of
thing.
Jul 13 '08 #8
Roy Smith <ro*@panix.comwrites:
Ben Finney <bi****************@benfinney.id.auwrote:
If you are passing a sequence conceptually, then it's more Pythonic to
pass it as a sequence explicitly::

def __init__(self, items):
""" Call with e.g. Stack(["foo", "bar"]) """
self.stack = list(items)

I don't get this. You're forcing a copy to be made of the list.
The 'items' object might not be a list; it might be some other
sequence. The rest of the class (as shown by the original poster)
requires it to be a list.
This changes the semantics of the original class, because the
operations no longer change the original list.
Which "original class" are you referring to? The one posted by the
original poster of this thread had no "original list"; it gathered the
positional arguments (using '*items') into an 'items' parameter, which
*doesn't exist* until the function body executes.

There *is* no "original list" in that implementation posed by the
original poster; it's constructed at call time from the positional
parameters to the function.

If anything, my implementation above *preserves* that semantic, by
making a new list from the passed-in sequence.

--
\ “Consider the daffodil. And while you're doing that, I'll be |
`\ over here, looking through your stuff.” —Jack Handey |
_o__) |
Ben Finney
Jul 13 '08 #9
In article <87************@benfinney.id.au>,
Ben Finney <bi****************@benfinney.id.auwrote:
Which "original class" are you referring to? The one posted by the
original poster of this thread had no "original list"; it gathered the
positional arguments (using '*items') into an 'items' parameter, which
*doesn't exist* until the function body executes.
Ah, I didn't notice that.
Jul 13 '08 #10

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

Similar topics

39
by: Erlend Fuglum | last post by:
Hi everyone, I'm having some trouble sorting lists. I suspect this might have something to do with locale settings and/or character encoding/unicode. Consider the following example, text...
3
by: George Young | last post by:
I have a bunch of blanket "except:" clauses like: class DatabaseError(StandardError): pass class OperationalError(StandardError): pass try: stuff except _pg.error, msg: raise...
13
by: KefX | last post by:
This may have been discussed before, but I'm kind of confused as to why Python doesn't support having both an except ~and~ a finally clause, like this: try: raise RuntimeException except:...
7
by: Robert Brewer | last post by:
Alex Martelli wrote in another thread: > One sign that somebody has moved from "Python newbie" to "good Python > programmer" is exactly the moment they realize why it's wrong to code: > > ...
0
by: John J. Lee | last post by:
Bare "except:", with no exception specified, is nasty because it can easily hide bugs. There is a case where it seemed useful to me in the past. Now it seems like a bad idea to me (but I think...
32
by: Rene Pijlman | last post by:
One of the things I dislike about Java is the need to declare exceptions as part of an interface or class definition. But perhaps Java got this right... I've writen an application that uses...
20
by: John Salerno | last post by:
I'm starting out with this: try: if int(text) 0: return True else: self.error_message() return False except ValueError: self.error_message()
35
by: Arnaud Delobelle | last post by:
Hi all, Imagine I have three functions a(x), b(x), c(x) that each return something or raise an exception. Imagine I want to define a function that returns a(x) if possible, otherwise b(x),...
5
by: Nebur | last post by:
I'm using the contract.py library, running Python 2.4.4. Now I'm confronted with the following exception backtrace: (...) File "/usr/lib/python2.4/site-packages/contract.py", line 1265, in...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
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:
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
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...

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.