> --
> http://mail.python.org/mailman/listinfo/python-list
>
>
Hi Andrew -
Sometimes you want an exception come up and then use that information to
take your
program in some direction. For example, you might want your program to
'see' the exception
that comes up when you go one beyond the end of an array. This means that
something you
wanted to happen within the array you set up finished successfully (the
program just reached one
beyond it and you didn't get an error!). The enduser doesn't need to see
this displayed on the screen
or in a window, you can just use an exception as-is to your advantage within
the program.
Regards,
Patty
In general, raise an exception when there is no valid value that can be
returned from a function. Sometimes it makes more sense to return 0,
None, an empty list, etc. So:
count_vowels("banana") ==> 3
count_vowels("xyzzy") ==> 0 # counting "y" as not a vowel
count_vowels("") ==> 0
count_vowels(None) ==> raises TypeError
You want to raise specific errors. Let's say you've got a function like
this:
def airspeed(swallow):
speeds = {"european": 42,
"african", 196}
return speeds[swallow]
If somebody passes an invalid string, it will raise KeyError as written.
Better to do something like:
def airspeed(swallow):
speeds = {"european": 42,
"african", 196}
try:
return speeds[swallow]
except KeyError:
raise UnknownBirdError(swallow)
This lets somebody catch UnknownBirdError at some higher level and do
something useful. If you let KeyError escape, that's a lot harder to
deal with because it could come from almost anywhere.
Generally speaking, a function or method should either do what it's
expected to do, returning the expected result, or raise an exception if
it can't.
Also, it's often clearer to distinguish between a function, which
returns a result, and a procedure, which doesn't (in Python it would
return None).
For example, if you have a list, the functional form is:
sorted(my_list)
which returns a new sorted list, and the procedural form is:
my_list.sort()
which sorts in-place (modifying the list) and returns None.
class HelloError(Exception):
pass
Of course, there are all sorts of other things you could do with your
exception.
http://docs.python.org/tutorial/errors.html#user-defined-exceptions
- --
Corey Richardson
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v2.0.17 (GNU/Linux)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org/
iQEcBAEBAgAGBQJNzED9AAoJEAFAbo/KNFvp1uQIAKFaKyD1Q3RL7LGFSmnyRFTK
9XWRH3CSM9mOALccfQ8bUkrquol1fAqhrm4jyOW0scWmsJpRlcb6Rj4HtrmMQOuG
DpsUzEZCTnT9Xk80OeTFbpWWBIVBkxdhCxCl75XAP22o5EjhHpgLyqoqMD+81BKH
5/JWAGRJx/9E4BvNWsxIUhb1jlz+XT4H1XykTE1UUOP0uZneWRJMs7P12WNiL2Ii
HT0hEUhQc1eP1fJ5BqPB/6/B9q/KxTbN55hCq1VwwfRhgbaM4kR7Bekri7QUHGAK
1MKxRa1v+Co59y+ywAIH92L3wky3xNyFrUlFzK4AwYOnwRkVvUWw7vPG1iShE+k=
=2+y6
-----END PGP SIGNATURE-----
You'll have to define it, as you would anything else (exceptions are
just regular "things"; in fact you can raise anything that's a class
or instance). I typically don't put a whole lot in my exception
classes, though.
point:~/working$ python
Python 2.6.2 (r262:71600, Jun 8 2009, 11:11:42)
[GCC 4.3.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> class HelloError(Exception): pass
...
>>> raise HelloError("hello!")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
__main__.HelloError: hello!
\t
Define it as a subclass of Exception:
class UnknownBirdError(Exception):
pass
class HelloError(Exception):
"custom exception"
and that's all you need. You can override __init__ to add your own
attributes, etc, if you need to.
~Ethan~
> On Thu, May 12, 2011 at 03:12:39PM -0500, Andrew Berg wrote:
>> On 2011.05.12 02:25 PM, MRAB wrote:
>> > You can raise an exception wherever you like! :-)
>> If I raise an exception that isn't a built-in exception, I get
>> something like "NameError: name 'HelloError' is not defined". I don't
>> know how to define the exception.
>
> You'll have to define it, as you would anything else (exceptions are
> just regular "things"; in fact you can raise anything that's a class or
> instance).
Not quite.
>>> raise 42
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: exceptions must be classes or instances, not int
Not a very good error message, because 42 is an instance!
>>> isinstance(42, int)
True
In Python 3, you get a better error message, and further restrictions on
what you can raise:
>>> raise 42
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: exceptions must derive from BaseException
In general, you should always subclass Exception rather than
BaseException. There are, er, exceptions, but for error-handling you
normally should inherit from Exception directly, or some sub-class like
ValueError, KeyError, etc.
--
Steven
> So that's where that info is. I wasn't looking in the tutorial
> section.
Does this mean you haven't worked through the tutorial? Time to remedy
that.
--
\ “You are welcome to visit the cemetery where famous Russian and |
`\ Soviet composers, artists, and writers are buried daily except |
_o__) Thursday.” —Russian orthodox monastery, Moscow |
Ben Finney